Php 多态表上按列列出的LAVEL顺序结果 简短问题
使用拉威尔雄辩的模型;如何按多个多态关系上的列对查询排序 更长的问题 假设我有给定的表结构:Php 多态表上按列列出的LAVEL顺序结果 简短问题,php,mysql,eloquent,laravel-5.2,Php,Mysql,Eloquent,Laravel 5.2,使用拉威尔雄辩的模型;如何按多个多态关系上的列对查询排序 更长的问题 假设我有给定的表结构: // table: images + -- + ------------ + -------------- + ----- + ----------- + | id | imageable_id | imageable_type | views | upload_date | + -- + ------------ + -------------- + ----- + ----------- + | 1
// table: images
+ -- + ------------ + -------------- + ----- + ----------- +
| id | imageable_id | imageable_type | views | upload_date |
+ -- + ------------ + -------------- + ----- + ----------- +
| 1 | 1 | User | 100 | 2016-16-06 |
| 2 | 3 | User | 200 | 2016-16-06 |
+ -- + ------------ + -------------- + ----- + ----------- +
// table: users
+ -- + ---- +
| id | name |
+ -- + ---- +
| 1 | Bob |
| 2 | Kat |
+ -- + ---- +
…我有一个雄辩的用户模型,有许多多态关系
我如何根据用户今天上传的图像接收到的浏览量对用户进行排序
我自己也尝试过这个问题,但没有找到解决方案。最接近正确顺序的是,我使用了与此类似的查询:
User::with([
'images' => function ($query) {
$query->where('upload_date', Carbon::today()->toDateString())
->orderBy('views', 'DESC');
}
])->get();
但是,在尝试了这一点之后,我很明显,用户现在按照递增的id而不是images表上的views列进行了错误的排序
提前感谢所有帮助我解决这个问题的人 多亏了这篇帖子上的评论,我才明白这一点
我以前尝试过类似的方法,但遇到了问题,因为ID和其他列在两个连接的表之间冲突。这次的区别在于->选择['users.*']。现在,只返回用户的数据。多亏了这篇文章上的一条评论,我才明白了这一点
我以前尝试过类似的方法,但遇到了问题,因为ID和其他列在两个连接的表之间冲突。这次的区别在于->选择['users.*']。现在,只返回用户的数据。或者,您也可以使用collections方法
或者,您也可以使用集合的方法
User::leftJoin('images', function ($join) {
$join->on('users.id', '=', 'images.imageable_id')
->where('imageable_type', '=', 'User')
->where('upload_date', '=', Carbon::today()->toDateString());
})
->orderBy('images.views')
->select(['players.*']);
$users = User::with([
'images' => function ($query) {
$query->where('upload_date', Carbon::today()->toDateString());
}
])->get()->sortByDesc(function ($user) {
return $user->images->views;
});