如何使用相关表对结果进行排序?
我有这个表:客户和经理(用户表)
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,它按客户端名称排序,但如果我尝试按联系人排序,则需要按用户(经理)的名称进行排序.