Laravel获取数据一对多关系与条件
Laravel Get data One to Many Relationship with conditions
如何将数据与条件的关系过多显示到视图中。
我有一个博客 post 有一条评论,但是这条评论有一个条件是发表与否。
这里是我的Post
模特
...
public function comments()
{
return $this->hasMany(Comment::class);
}
...
在我上面的代码中,我可以简单地使用 $post->comments
来显示所有评论。
就像我之前说的,我只需要显示已发布的评论 true
但是如何添加条件呢?...
您只能使用
获取已发布的评论
$this->post->comments()->where('published', true)->get()
Of course, since all relationships also serve as query builders, you can add further constraints to which comments are retrieved by calling the comments method and continuing to chain conditions onto the query: $comment = App\Post::find(1)->comments()->where('title', 'foo')->first();
您可以通过获取 post 及其已发布的评论来实现此目的;
$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);
}
如何将数据与条件的关系过多显示到视图中。
我有一个博客 post 有一条评论,但是这条评论有一个条件是发表与否。
这里是我的Post
模特
...
public function comments()
{
return $this->hasMany(Comment::class);
}
...
在我上面的代码中,我可以简单地使用 $post->comments
来显示所有评论。
就像我之前说的,我只需要显示已发布的评论 true
但是如何添加条件呢?...
您只能使用
获取已发布的评论
$this->post->comments()->where('published', true)->get()
Of course, since all relationships also serve as query builders, you can add further constraints to which comments are retrieved by calling the comments method and continuing to chain conditions onto the query:
$comment = App\Post::find(1)->comments()->where('title', 'foo')->first();
您可以通过获取 post 及其已发布的评论来实现此目的;
$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);
}