FabienChn
FabienChn

Reputation: 968

Laravel relationship with pivot table

I have 3 tables in my database :

users (id);
interests (id);
users_interests (user_id, interests_id);

I want to be able to fetch all the user's interests in this way :

$interests = $user->interests

This is what I wrote in the User.php model, following laravel's doc:

public function interests() { 
    return $this->hasManyThrough(
         'App\Interest', 'App\UserInterest', 
         'user_id', 'id', 'interest_id'
    );
}

but it returns empty even though the user has a game. So there has to be something I'm doing wrong

Anyone to help me ?

Upvotes: 0

Views: 3143

Answers (1)

ka_lin
ka_lin

Reputation: 9442

I think a belongs to many would do the job:

public function interests() { 
    return $this->belongsToMany(
         'App\Interest', 
         'users_interests', 
         'user_id', 
         'interests_id'
    );
}

Quite similar to the example in the docs

If you were to rename users_interests table to interest_user and the column interests_id to the singular form you would just need the first parameter:

 public function interests() { 
        return $this->belongsToMany(App\Interest::class);
    }

From my understanding the hasManyThrough is used to jump forward within a relation (also described in the docs):

The "has-many-through" relationship provides a convenient shortcut for accessing distant relations via an intermediate relation.

Upvotes: 3

Related Questions