加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > MySql教程 > 正文

php – Laravel排序关系

发布时间:2020-12-11 23:37:17 所属栏目:MySql教程 来源:网络整理
导读:如何使用相关表对结果进行排序? 我有这个表:客户和经理(用户表) Client.php Users.php是默认的Laravel模型. 我的问题是如何查询表客户端按Manager的名称排序. 到目前为止,这是我的代码: public function getClients() { // Sorting preparations $allowed

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

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

Client.php

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语句中

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读