Laravel MySQL orderBy count

前端 未结 2 1772
南方客
南方客 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();
    

提交回复
热议问题