【问题标题】:Laravel Get data One to Many Relationship with conditionsLaravel 获取数据与条件的一对多关系
【发布时间】:2018-09-10 00:50:20
【问题描述】:

如何显示数据与条件的关系。

我有一篇有评论的博文,但这条评论的条件是发表与否。

这是我的Post 模特

...

public function comments()
{
    return $this->hasMany(Comment::class);
}
...

在我上面的代码中,我可以简单地使用 $post->comments 来显示所有 cmets。

就像我之前说的,我只需要显示 cmets 并发布为 true

但是如何添加条件呢?...

【问题讨论】:

    标签: php laravel laravel-5.5


    【解决方案1】:

    您可以通过获取带有已发布 cmets 的帖子来实现此目的;

    $post = Post::where('id', $id)->with('comments', function ($q) { 
         $q->where('published', true);
    })->first(); 
    

    那么当你在视图中调用 $post->cmets 时,你只会得到发布的那个。

    或者,如果您真的愿意,您可以更新您的模型以具有已发布的 cmets 关系,但不建议这样做。

    public function publishedComments()
    {
        return $this->hasMany(Comment::class)->where('published', true);
    }
    

    【讨论】:

      【解决方案2】:

      使用
      $this->post->comments()->where('published', true)->get()只能获取已发布的cmets

      查看Documentation

      当然,由于所有关系都可以用作查询构建器,因此您可以通过调用 cmets 方法并继续将条件链接到查询上来添加更多的约束条件来检索 cmets:$comment = App\Post::find(1)->comments()->where('title', 'foo')->first();

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2015-04-05
        • 2019-07-17
        • 2017-07-16
        • 2015-07-20
        • 2020-07-28
        • 1970-01-01
        • 2022-01-11
        相关资源
        最近更新 更多