Laravel MySQL orderBy count

前端 未结 2 1768
南方客
南方客 2021-02-09 08:25

I\'m using Laravel and MySQL, and I have a table post that represents post where users can comment on it, now I wanna order posts by the number of comments of each post

2条回答
  •  鱼传尺愫
    2021-02-09 08:53

    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

提交回复
热议问题