Answer the question
In order to leave comments, you need to log in
How to sort by field?
Good evening!
There are two tables: posts (id, name, text) and comments (id, text, post_id)
How to sort posts by number of comments?
Found and tried via join:
$posts = Post::with('comments')
->join('comments', 'comments.post_id', '=', 'posts.id')
->select('posts.*', 'comments.*')
->groupBy('posts.id')
->orderBy(DB::raw('COUNT(`posts`.`id`)'), 'asc')
->get();
Answer the question
In order to leave comments, you need to log in
We assume that there is a Post model with a comments() relation that hasMany
$postsWithCountOfComments = Post::withCount("comments")->get();
$sortedPosts = $postsWithCountOfComments->sortByDesc('comments_count');
1. If groupBy('posts.id'), then you cannot select('comments.*'). For it is ambiguous
Generally speaking, at groupBy ('posts.id') it is possible only select ('posts.id') + group functions. Although MySQL will skip some shitty code, that's no reason to write it that way.
2. The number of comments is COUNT(comments.post_id) or simply COUNT(*). And COUNT(posts.id) with GROUP BY posts.id - obviously, it will always be 1
3. If it's still an error, then specify the resulting SQL
4. Well, in general, the correct way is to create a new posts.count_comments field with an index and recalculate it when comment change.
SELECT COUNT ( id ) AS cntd
FROM comments
GROUP BY post_id
ORDER BY cntd
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question