Laravel MySQL orderBy count

时间秒杀一切 提交于 2019-12-03 07:23:37

You can do that as you showed but now you get all entries from database. If you will have 100 posts each with 100 comments, you will get 10000 rows from your database just to sort your posts (I assume you don't want to display those comments when sorting).

You could add to your Post model:

public function commentsCountRelation()
{
    return $this->hasOne('Comment')->selectRaw('post_id, count(*) as count')
        ->groupBy('post_id');
}

public function getCommentsCountAttribute()
{

    return $this->commentsCountRelation ?
        $this->commentsCountRelation->count : 0;
}

and now you could use:

$posts = Post::with('commentsCount')->get()->sortBy(function($post) {
    return $post->comments_count;
});

to sort ascending or

$posts = Post::with('commentsCount')->get()->sortBy(function($post) {
    return $post->comments_count;
}, SORT_REGULAR, true);

to sort descending.

By the way using sortBy and later reverse is not a good idea you should use parameters to sortBy as I showed

I think I've come up with a workaround:

$posts = Post::with('comments')->get()->sortBy(function($post) {
    return $post->comments->count();
});

This one order by the number of comments ascendingly, if you want to order by it descendingly, do this:

$posts = Post::with('comments')->get()->sortBy(function($post) {
    return $post->comments->count();
})->reverse();
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!