Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/246.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php Laravel获得与条件相关的一对多数据_Php_Laravel_Laravel 5.5 - Fatal编程技术网

Php Laravel获得与条件相关的一对多数据

Php Laravel获得与条件相关的一对多数据,php,laravel,laravel-5.5,Php,Laravel,Laravel 5.5,如何在视图中显示一个或多个具有条件的关系的数据 我有一篇有评论的博客文章,但这篇评论有一个条件,即是否发布 这里是我的Post型号 ... public function comments() { return $this->hasMany(Comment::class); } ... 在上面的代码中,我可以简单地使用$post->comments显示所有注释 就像我之前说过的,我只需要显示带有published istrue的注释 但是如何添加条件?…使用 $this->po

如何在视图中显示一个或多个具有条件的关系的数据

我有一篇有评论的博客文章,但这篇评论有一个条件,即是否发布

这里是我的
Post
型号

...

public function comments()
{
    return $this->hasMany(Comment::class);
}
...
在上面的代码中,我可以简单地使用
$post->comments
显示所有注释

就像我之前说过的,我只需要显示带有published is
true的注释


但是如何添加条件?…

使用
$this->post->comments()->where('published',true)->get()

检查

当然,由于所有关系也充当查询生成器,您可以通过调用comments方法并继续将条件链接到查询上来添加检索注释的进一步约束:
$comment=App\Post::find(1)->comments()->where('title',foo')->first()


使用
$this->post->comments()->where('published',true)->get()

检查

当然,由于所有关系也充当查询生成器,您可以通过调用comments方法并继续将条件链接到查询上来添加检索注释的进一步约束:
$comment=App\Post::find(1)->comments()->where('title',foo')->first()


你可以通过发布评论来获取帖子

$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::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);
}