php – Laravel排序关系

前端之家收集整理的这篇文章主要介绍了php – Laravel排序关系前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

如何使用相关表对结果进行排序?

我有这个表:客户和经理(用户表)

Client.PHP

PHP

class Client extends Eloquent {
    protected $table = 'clients';

    public function Manager(){
        return $this->belongsTo('User','manager','id');
    }
    public function Transaction(){
        return $this->hasMany('ClientTransaction','client','id');
    }
}

Users.PHP是默认的Laravel模型.

我的问题是如何查询表客户端按Manager的名称排序.

到目前为止,这是我的代码

public function getClients() {
    // Sorting preparations
    $allowed    = array('name','contact','money');
    $sort       = in_array(Input::get('sort'),$allowed) ? Input::get('sort') : 'name';
    $order      = Input::get('order') === 'desc' ? 'desc' : 'asc';
    // Get Clients from DB
    if($sort == 'contact'){
        $clients    = Client::with(array('Manager' => function($query) use ($order) {
            $query->orderBy('name',$order);
        }));
    } else {
        $clients    = Client::orderBy($sort,$order)->with('Manager');
    }
    // Filters
    $cname      = null;
    if(Input::has('cname')){
        $clients    = $clients->where('name',Input::get('cname'));
        $cname      = '$cname='.Input::get('cname');
    }
    // Pagination
    $clients    = $clients->paginate(25);
    // Return View
    return View::make('pages.platform.clients')
        ->with('clients',$clients);
}

如果我按名称尝试sord,它按客户端名称排序,但如果我尝试按联系人排序,则需要按用户(经理)的名称进行排序.

最佳答案
试试这个.

$clients = Client::join('users as manager','manager.id','=','clients.manager')
            ->orderBy('manager.name',$order)
            ->select('clients.*') // avoid fetching anything from joined table
            ->with('Manager');  // if you need managers data anyway

如果($sort ==’contact’){/ *** /},请将其放入if语句中

猜你在找的MySQL相关文章