【发布时间】:2019-06-23 10:14:53
【问题描述】:
我想在其他相关表上按字段排序 eloquent 的结果。 我有用户表。每个用户都有一个配置文件。配置文件有赞助(这是布尔值)字段。因此,当我想获得所有用户时,我想首先显示赞助用户,然后是非赞助用户。
public function profile(){
return $this->hasOne('App\Doctor');
}
【问题讨论】:
我想在其他相关表上按字段排序 eloquent 的结果。 我有用户表。每个用户都有一个配置文件。配置文件有赞助(这是布尔值)字段。因此,当我想获得所有用户时,我想首先显示赞助用户,然后是非赞助用户。
public function profile(){
return $this->hasOne('App\Doctor');
}
【问题讨论】:
有两种方法: 1)你必须加入表格,
User::join('profiles','users.id','=','profile.user_id')->orderBy('sponsored','DESC')->get()
2)通过预加载排序
User::with(array('profile' => function($query) {
$query->orderBy('sponsored', 'DESC');
}))
->get();
【讨论】:
试试这个
User::leftJoin('profile', 'user.id', '=', 'profile.user_id')
->orderBy('profile.sponsored', 'ASC')
->get();
【讨论】:
我强烈建议不要使用表连接,因为它会让你在规模上失败。
更好的解决方案是获取用户,获取他们的个人资料,然后使用 laravel 收集方法对其进行排序。
您可以使用此示例来实现此解决方案。
//get all users
$users = User::all();
//extract your users Ids
$userIds = $users->pluck('id')->toArray();
//get all profiles of your user Ids
$profiles = Profile::whereIn('user_id', $userIds)->get()->keyBy('user_id');
//now sort users based on being sponsored or not
$users = $users->sort(function($item1, $item2) use ($profiles) {
if($profiles[$item1->id]->sponsored == 1 && $profiles[$item2->id]->sponsored == 1){
return 0;
}
if($profiles[$item1->id]->sponsored == 1) return 1;
return -1;
});
您可以查看this link,它解释了 laravel 集合排序。
【讨论】:
$order = 'desc';
$users = User::join('profile', 'users.id', '=', 'profile.id')
->orderBy('profile.id', $order)->select('users.*')->get();
【讨论】: