Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel get second level relations

I have three database tables:

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

Each user can have many types, but one user type can only have one user. To store this relation, I use a third relationship table, with the following structure:

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

I have defined the relations in my models like so:

User model:

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

UserType model:

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

UserTypeRelations model:

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

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

And this is how I try to access the user type of a specific user in my controller, before passing it to a view:

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

I thought that first I get the relation table's value, and from that I'll easily get the User Type of each User, but I get the following error:

BadMethodCallException

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

What am I doing wrong?

like image 338
Peter Avatar asked Dec 24 '22 20:12

Peter


1 Answers

You can eager load multiple nested relations to a model by passing them both to a single call to with:

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

Source

like image 75
Jeff Lambert Avatar answered Dec 27 '22 08:12

Jeff Lambert