简体   繁体   English

调整雄辩的关系-每个父母如何获得N个相关模型?

[英]Tweaking Eloquent relations – how to get N related models per parent?

How to get 2 latest comments of each post? 如何获得每个帖子的2条最新评论? I use laravel 5.2 and Postgres 我使用laravel 5.2和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. 我想获得所有带有最新2条评论的帖子。 How can I do this with Eloquent. 我该如何使用Eloquent。 Thanks in advance! 提前致谢!

You need to define additional relation in your Post model that will return 2 latest comments : 您需要在Post模型中定义其他关系,该关系将返回2条最新评论

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 ; 现在,对于每个帖子,您都可以使用$ post-> latest_comments访问其2条最新评论;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM