按急切加载的关系计数排序
Order by eager loaded relation count
我有这样的东西
class Item extends Model
{
...
public function likes() {
return $this->hasMany('like');
}
...
在我的控制器中,我像这样加载这个项目
$items = Item::with([
...
'likes',
'comments',
...
])
->paginate(10);
我需要计算点赞数并按此数字分页排序此列表,类似这样
$items = Item::with([
...
'likes',
'comments',
...
])
->orderBy(likes->count())
->paginate(10);
,这显然是行不通的。有小费吗 ?谢谢
只是一个解决方案。但我认为有一个更好的
$items = Item::with([
...
'likes',
'comments',
...
])
->withCount('likes')
->orderBy('likes_count','DESC')
->paginate(10);
试试这个看看你是否得到你想要的输出
$items = Item::with([
...
'likes'=>function($query){
$query->selectRaw('likes.*,count(likes.LikeID) as LikesCount')->groupBy('Item.itemID');
},
'comments',
...
])
->orderBy('likes.Likescount','DESC')
->paginate(10);
我有这样的东西
class Item extends Model
{
...
public function likes() {
return $this->hasMany('like');
}
...
在我的控制器中,我像这样加载这个项目
$items = Item::with([
...
'likes',
'comments',
...
])
->paginate(10);
我需要计算点赞数并按此数字分页排序此列表,类似这样
$items = Item::with([
...
'likes',
'comments',
...
])
->orderBy(likes->count())
->paginate(10);
,这显然是行不通的。有小费吗 ?谢谢
只是一个解决方案。但我认为有一个更好的
$items = Item::with([
...
'likes',
'comments',
...
])
->withCount('likes')
->orderBy('likes_count','DESC')
->paginate(10);
试试这个看看你是否得到你想要的输出
$items = Item::with([
...
'likes'=>function($query){
$query->selectRaw('likes.*,count(likes.LikeID) as LikesCount')->groupBy('Item.itemID');
},
'comments',
...
])
->orderBy('likes.Likescount','DESC')
->paginate(10);