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


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

如何获取每个帖子的2条最新评论?我使用的是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 |
+-----+---------------------+---------+

我想要得到最近2个评论的所有帖子。我怎么能做到这一点雄辩。提前感谢!

您需要在Post模型中定义额外的关系,该关系将返回2个最新评论:

class Post extends Model {
  public function latest_comments() {
    return $this->hasMany(Comment::class)->take(2)->orderBy('created_at', 'desc');
  }
}

现在,对于每个帖子,您可以使用$post->latest_comments;

访问它的2个最新评论