rtheunissen
rtheunissen

Reputation: 7435

Can't get Eloquent's hasManyThrough to work for a basic example

Here are my relationships:

User

Collection

UserCollection

How can I get something like $user->collections to return all Collection objects that belongs to the user? A UserCollection simply links a User to a Collection. This allows a user to have multiple collections, but also allows a collection to belong to multiple users.

What I'm currently trying is to specify that UserCollection belongs to a User on user_id, and belongs to a Collection on collection_id.

// UserCollection

public function user()
{
    return $this->belongsTo(User::class, 'user_id');
}

public function collection()
{
    return $this->belongsTo(Collection::class, 'collection_id');
}

Then specifying that a User has many Collections through UserCollection.

// User

public function collections()
{
    return $this->hasManyThrough(Collection::class, UserCollection::class);
}

I've also tried explicitly setting the column names of the hasManyThrough relationship, but the join tries to use an id column on the UserCollection model, which does not exist as there is no primary key:

public function collections()
{
    return $this->hasManyThrough(Collection::class, UserCollection::class, 'user_id', 'collection_id');
}

Upvotes: 1

Views: 1386

Answers (1)

lukasgeiter
lukasgeiter

Reputation: 152860

You're overcomplicating things here. You don't need hasManyThrough. What you need is belongsToMany() for a many-to-many relationship.

First, get rid of your UserCollection model. You don't need it.

Then change your relations to this:

public function collections(){
    return $this->belongsToMany('Collection', 'user_collections');
}

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

For more information take a look at the official docs on relations

Upvotes: 2

Related Questions