【问题标题】:How to create a "has many through" relationship with 4 tables with laravel 5.3如何使用 laravel 5.3 创建与 4 个表的“多通”关系
【发布时间】:2018-07-26 09:12:48
【问题描述】:

在 laravel 中,您可以使用 3 个表创建 "has-many-through" 关系。

我想知道是否可以用 4 个表创建这样的关系,如果可以,如何?

感谢question,我知道如何使用 sql 语法来做到这一点,但我想先使用 laravel 标准解决方案。

感谢您的帮助。

示例

4 个表格:国家、用户、帖子、评论

countries
    id - integer
    name - string

users
    id - integer
    country_id - integer
    name - string

posts
    id - integer
    user_id - integer
    title - string

comments
    id - integer
    post_id - integer
    title - string
    body - string

我想做以下事情,列出一个国家的所有 cmets。

$country = Country::first();
$country->comments;

【问题讨论】:

  • 这个 i laravel 没有任何办法......在性能上这个查询真的很糟糕......但如果你愿意,你可以使用 join 手动创建该查询

标签: php laravel


【解决方案1】:

与 4 个表没有 hasManyThrough 关系。但是,你可以使用Nested eager loading

$country = Country::with('users.posts.comments')->first();

【讨论】:

  • 感谢您的回答,我没想到嵌套的急切加载。
【解决方案2】:

我创建了一个无限级别的HasManyThrough 关系:Repository on GitHub

安装后,可以这样使用:

class Country extends Model {
    use \Staudenmeir\EloquentHasManyDeep\HasRelationships;

    public function comments() {
        return $this->hasManyDeep(Comment::class, [User::class, Post::class]);
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-05-24
    • 2017-05-31
    • 1970-01-01
    • 2021-11-10
    • 2017-05-13
    • 2021-01-09
    • 2017-05-19
    相关资源
    最近更新 更多