Reputation: 597
How to get 2 latest comments of each post? I use laravel 5.2 and Postgres
My comments table
+-----+---------------------+---------+
| id | created_at | post_id |
+-----+---------------------+---------+
| 344 | 2014-08-17 21:25:46 | 1 |
| 320 | 2014-08-17 21:25:45 | 1 |
| 4 | 2014-08-17 21:25:26 | 1 |
| 72 | 2014-08-17 21:25:29 | 1 |
| 158 | 2014-08-17 21:25:37 | 2 |
| 423 | 2014-08-17 21:25:50 | 2 |
| 59 | 2014-08-17 21:25:29 | 2 |
| 227 | 2014-08-17 21:25:40 | 2 |
| 308 | 2014-08-17 21:25:45 | 3 |
| 34 | 2014-08-17 21:25:28 | 3 |
+-----+---------------------+---------+
My posts table
+-----+---------------------+---------+
| id | created_at | title |
+-----+---------------------+---------+
| 1 | 2014-08-17 21:25:46 | a |
| 2 | 2014-08-17 21:25:45 | b |
| 3 | 2014-08-17 21:25:26 | c |
+-----+---------------------+---------+
I want to get all posts with latest 2 comments. How can I do this with Eloquent. Thanks in advance!
Upvotes: 0
Views: 147
Reputation: 40919
You need to define additional relation in your Post model that will return 2 latest comments:
class Post extends Model {
public function latest_comments() {
return $this->hasMany(Comment::class)->take(2)->orderBy('created_at', 'desc');
}
}
Now, for every post, you can access its 2 latest comments with $post->latest_comments;
Upvotes: 1