Laravel MySQL orderBy count

前端 未结 2 1773
南方客
南方客 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:46

    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();
    
    0 讨论(0)
  • 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

    0 讨论(0)
提交回复
热议问题