如何使用相关表格对结果进行排序?
我有这些表:Clients
和Managers
(用户表)
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模型。
我的问题是如何查询表客户端按管理员名称排序。
到目前为止,这是我的代码:
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,它按客户端名称排序,但如果我尝试按联系排序,则需要按用户(经理)的名称进行排序。
答案 0 :(得分:10)
试试这个。
$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
将此内容放入if语句if($sort == 'contact'){ /***/ }