如何使用相关表对结果进行排序?
我有这个表:客户和经理(用户表)
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);
}
最佳答案
试试这个.
原文链接:https://www.f2er.com/mysql/433485.html$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语句中