Laravel 获取二级关系

Pet*_*ter 4 php model-view-controller orm database-relations laravel

我有三个数据库表:

+------+-----------+---------------------+
| user | user_type | user_type_relations |
+------+-----------+---------------------+
Run Code Online (Sandbox Code Playgroud)

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

+---------------------+
| user_type_relations |
+---------------------+
| id                  |
| user_id             |
| user_type_id        |
+---------------------+
Run Code Online (Sandbox Code Playgroud)

我已经定义了我的模型中的关系,如下所示:

User 模型:

public function userTypeRelations()
    {
        return $this->hasMany('UserTypeRelations', 'user_id', 'id');
    }
Run Code Online (Sandbox Code Playgroud)

UserType 模型:

public function userTypeRelation()
    {
        return $this->hasMany('UserTypeRelations', 'user_type_id', 'id');
    }
Run Code Online (Sandbox Code Playgroud)

UserTypeRelations 模型:

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

    public function userType()
    {
        return $this->hasMany('UserType', 'id', 'user_type_id');
    }
Run Code Online (Sandbox Code Playgroud)

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

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

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

BadMethodCallException

Call to undefined method Illuminate\Database\Query\Builder::userType() 
Run Code Online (Sandbox Code Playgroud)

我究竟做错了什么?

Jef*_*ert 8

您可以通过将多个嵌套关系传递给单个调用来急切地将多个嵌套关系加载到模型中with

User::with('userTypeRelations.userType') ...
Run Code Online (Sandbox Code Playgroud)

来源