【发布时间】:2017-10-04 14:22:44
【问题描述】:
我试图限制 laravel 中的 hasMany 关系,但不是每个帖子,而是限制整个或所有记录。下面是我的解释代码。
class Post extends Model {
protected $table = "user_posts";
protected $appends = ['logged_in_user_id', 'comments_count'];
public function user() {
return $this->belongsTo('App\User');
}
public function comments() {
return $this->hasMany('App\Comment')->take(2);
}
}
我正在尝试在每个帖子上获得 2 或 3 条最新评论,如下所示
$posts = \App\Post::orderBy('updated_at', 'DESC')->with('comments')->where('user_posts.user_id', $user_id)->paginate(10);
问题不是为每个帖子提供 2 条评论,而是从所有获取的帖子中只提供 2 条评论。
当前结果:
帖子1:
- 评论1
- 评论2
帖子2: 帖子 2 中没有加载评论,因为它限制了整体。
预期:
post1:
- 评论1
- 评论2
post2:
- 评论1
- 评论2
【问题讨论】:
-
试试这个
\App\Post::orderBy('updated_at', 'DESC')->with(['comments' => function($q) { $q->take(2); }])->get();!! -
我试过了,但我给出了相同的结果
-
明显的问题 post2 有 cmets 吗??
-
是的 id 确实有
标签: php laravel laravel-5 eloquent