【问题标题】:Query relationship values from a collection从集合中查询关系值
【发布时间】:2018-03-28 02:56:20
【问题描述】:

我有 3 个表,用户 > 帖子 > cmets。用户有很多帖子,帖子有很多 cmets。我试图从用户那里只获取 cmets。像这样的:

$user->posts->comments->where(...)->get()
  • $user->posts 返回帖子集合的集合
  • 因此,如果我尝试$user->posts->first()->comments,它会返回帖子的 cmets 集合。

但是,对于上述情况 (posts->comments),它不起作用,因为帖子是一个集合

我相信运行 for 循环不是最佳方式,尽管我相信可以通过这种方式实现。

Laravel 的实现方式是什么?

【问题讨论】:

    标签: php laravel collections eloquent relationship


    【解决方案1】:

    您可以使用 Has Many Through,请参阅 https://laravel.com/docs/5.5/eloquent-relationships#has-many-through

    在您的用户模型中:

    public function comments()
    {
        return $this->hasManyThrough('App\Comment', 'App\Post');
    }
    

    【讨论】:

    • 非常感谢!不敢相信我错过了
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-12-06
    • 2019-01-04
    • 2013-08-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-07
    相关资源
    最近更新 更多