如何显示数据与条件的太多关系进入视图。
我有一篇有评论的博客文章,但这条评论的条件是否已发布。
在这里我的Post
模型
...
public function comments()
{
return $this->hasMany(Comment::class);
}
...
在上面的代码我可以简单地使用$post->comments
来显示所有的评论。
就像我之前说的那样,我只需要发表评论,发表的是true
但如何添加条件?...
你可以通过发表评论的帖子来实现这一点;
$post = Post::where('id', $id)->with('comments', function ($q) {
$q->where('published', true);
})->first();
然后,当您在视图中调用$ post-> comments时,您将只获得已发布的一个。
或者,如果您真的想要,您可以更新您的模型以获得已发布的评论关系,但建议不要这样做。
public function publishedComments()
{
return $this->hasMany(Comment::class)->where('published', true);
}
您只能使用已发布的评论
$this->post->comments()->where('published', true)->get()
当然,由于所有关系也充当查询构建器,您可以通过调用comments方法并继续将条件链接到查询来添加更多约束以检索哪些注释:
$comment = App\Post::find(1)->comments()->where('title', 'foo')->first();