按热切加载关系计数排序


Order by eager loaded relation count

我有这样的东西

class Item extends Model
{   
    ...
    public function likes() {
    return $this->hasMany('like');
}
...

在我的控制器中,我像这样加载这个项目

$items = Item::with([
        ...
        'likes',
        'comments',
        ...
    ])
        ->paginate(10);

我需要得到like count并对这个列表排序并按这个数字分页就像这样

$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);