BugHunterUK
BugHunterUK

Reputation: 8938

Eloquent - Having problems using eager loading on nested relationships

I'm trying to eager load nested relationships, but I'm having trouble returning the correct results.

Here are the models:

User.php

class User extends Model
{
    public function universities()
    {
        return $this->hasMany('\StudentApp\Models\UserUniversity');
    }
}

UserUniversity.php

class UserUniversity extends Model
{
    protected $fillable = [ 'user_id', 'university_id', 'choice' ];

    public function university()
    {
        return $this->hasOne('\StudentApp\Models\University');
    }
}

University.php

class University extends Model
{
    protected $table = 'university';
}

What I want to do is get a user by ID, fetch the users universities from the UserUniversity pivot table, and then fetch the name of that university from the University table.

I've tried the following to test if it works:

$user = User::with('universities')->find($this->jwtObject->uid);
return $response->withJson($user->universities[0]->university);

But I get the following error:

Column not found: 1054 Unknown column 'university.user_university_id' in 'where clause' (SQL: select * from `university` where `university`.`user_university_id` = 10 and `university`.`user_university_id` is not null limit 1) [] {"uid":"28c5a97"}

user.user_university_id is incorrect. That column doesn't exist and I'm not sure why it's trying to use that column.

What it should be using is user.university_id

How can I do this?

Upvotes: 2

Views: 1287

Answers (2)

Buglinjo
Buglinjo

Reputation: 2076

You should add foreign key and primary key in relation:

public function universities()
{
    return $this->hasMany('\StudentApp\Models\University', 'university_id', 'id');
}

Upvotes: 4

Alexey Mezenin
Alexey Mezenin

Reputation: 163748

Correct nested eager loading syntax is:

User::with('universities.university')

Also, make sure you've using the correct foreign key in the university table:

user_university_id

Or define another key in the relationship:

public function university()
{
    return $this->hasOne('\StudentApp\Models\University', 'another_foreign_key');
}

Upvotes: 0

Related Questions