Laravel 排序关系

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25123568/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 09:54:20  来源:igfitidea点击:

Laravel sort Relationship

phpmysqllaravellaravel-4

提问by Milos Miskone Sretin

How can I sort my result with related tables?

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

I have this tables: Clientsand Managers(users table)

我有这个表:ClientsManagers(用户表)

Client.php

客户端.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(default Laravel's model)

Users.php(默认 Laravel 模型)

My question is how can I query table clients to be sorted by Manager's name.

我的问题是如何查询要按经理名称排序的表客户端。

Here is my code so far:

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

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);
}

If I try to sort by Name it sorts OK by Clients name but if I try to sort by contact it needs to sort by User's (Manager's) name.

如果我尝试按名称排序,它可以按客户名称排序,但如果我尝试按联系人排序,则需要按用户(经理)的姓名排序。

回答by Milos Miskone Sretin

Try this.

尝试这个。

$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

Put this into your if statement if($sort == 'contact'){ /***/ }

把它放到你的 if 语句中 if($sort == 'contact'){ /***/ }