'laravel latest or order by not working from a related table
I have my code here. I just want to sort it according to the latest comments posted.
$comments = ModelsComment::with('Comments')->where('posts_id', $this->post)
->WhereHas('Comments', function ($q){
$q->orderBy('created_at', 'DESC'); //->latest()
})->paginate('5');
ModelsComment is my pivot table(no time stamps here) so i'm trying to sort it by newest comments added(Related table).
However, oldest record is still appearing from the top. Any help would be appreciated.
My Table structure looks like this
POST
id
name
timestamps
ModelsComment(without timestamps)
posts_id
comments_id
Comments
id
name
timestamps
I'm trying to query from my ModelsComment, and order the Comments table with the latest/newest entry first.
Solution 1:[1]
Use this version:
$comments = ModelsComment::with(['Comments' => function ($q) {
$q->orderBy('created_at', 'DESC')
}])
->paginate('5')
->get();
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
