【问题标题】:Laravel get second level relationsLaravel 获得二级关系
【发布时间】:2015-06-29 04:59:24
【问题描述】:

我有三个数据库表:

+------+-----------+---------------------+
| user | user_type | user_type_relations |
+------+-----------+---------------------+

每个用户可以有多种类型,但一种用户类型只能有一个用户。为了存储这个关系,我使用了第三个关系表,结构如下:

+---------------------+
| user_type_relations |
+---------------------+
| id                  |
| user_id             |
| user_type_id        |
+---------------------+

我在我的模型中定义了这样的关系:

User模特:

public function userTypeRelations()
    {
        return $this->hasMany('UserTypeRelations', 'user_id', 'id');
    }

UserType模特:

public function userTypeRelation()
    {
        return $this->hasMany('UserTypeRelations', 'user_type_id', 'id');
    }

UserTypeRelations模特:

 public function user()
    {
        return $this->hasMany('User', 'id', 'user_id');
    }

    public function userType()
    {
        return $this->hasMany('UserType', 'id', 'user_type_id');
    }

这就是我尝试在控制器中访问特定用户的用户类型,然后将其传递给视图的方式:

$users = User::with('userTypeRelations')->with('userType')->orderBy($order)->where('status', 'active')->paginate(10);

我以为首先我会得到关系表的值,然后我会很容易地得到每个用户的用户类型,但是我得到了以下错误:

BadMethodCallException

Call to undefined method Illuminate\Database\Query\Builder::userType() 

我做错了什么?

【问题讨论】:

    标签: php laravel model-view-controller orm database-relations


    【解决方案1】:

    您可以通过将 multiple 嵌套关系传递给对 with 的单个调用来将它们急切加载到模型中:

    User::with('userTypeRelations.userType') ...
    

    Source

    【讨论】:

    • 谢谢,不知道这个。对不起,如果我不清楚,但我想做的是首先获取 userTypeRelation,然后从返回的 ID 中获取用户类型。所以这就是为什么我称之为二级(不确定这个词是否正确)。
    • + 我通过一次调用 with 修改了我的代码,但我仍然遇到同样的错误
    • 好的,我更新了代码。我相信 Laravel 文档中他们称这些为 nested 关系。看看这是否适合你。
    【解决方案2】:

    我相信你们的关系是错误的。这实际上是多对多关系,这意味着您可以一起摆脱您的UserTypeRelations

    话虽如此,删除UserTypeRelations.php,然后假装该关系不再存在。 Laravel 将为您处理该表。

    然后在你的用户模型中,创建函数...

    public function types()
    {
        return $this->belongsToMany('UserType', 'user_type_relations','user_type_id', 'user_id');
    }
    

    并在您的 UserType 模型中添加函数...

    public function users()
    {
        return $this->belongsToMany('User', 'user_type_relations', 'user_id', 'user_type_id');
    }
    

    现在它不再是嵌套关系。

    $user = User::with('types')->find($id);
    foreach($user->types as $type) {
        echo $type;
    }
    

    【讨论】:

    • 不错,我相信这对 OP 来说更好
    • 是的,从给定的信息来看,OP 正在尝试手动创建数据透视表,但 Laravel 想要自动执行此操作
    猜你喜欢
    • 1970-01-01
    • 2015-03-09
    • 1970-01-01
    • 1970-01-01
    • 2022-01-01
    • 2017-05-06
    • 2020-01-15
    • 2021-03-10
    相关资源
    最近更新 更多