I have posts and comments tables in my database. Comments table has posts id as foreign key. Now if I want to sort posts with most comments, how can i do that in laravel?
Asked
Active
Viewed 1,738 times
0
-
please add code of what you're using to get users and comments – Sérgio Reis Jun 02 '17 at 11:59
-
1Pretty sure this is what you're trying to achieve https://stackoverflow.com/a/24208979/5844171 – Sérgio Reis Jun 02 '17 at 12:02
-
it's not duplicate of that question. those two questions are totally different @rbaskam – yasaryousuf Mar 14 '18 at 11:00
1 Answers
8
This sorts the post by their comment count.
$posts = Post::withCount('comments')
->orderBy('comments_count', 'desc')
->get();

Sandeesh
- 11,486
- 3
- 31
- 42