Alexxosipov
Alexxosipov

Reputation: 1234

Many to Many Relation with custom pivot table

I have 4 tables in project's database:

users (id, name)
teams (id, name)
team_members (id, user_id, team_id)
team_member_permissions (team_member_id, team_id)

I need to get user's teams. My current solution is to create teamMembers relationship in User model:

public function teamMembers()
{
    return $this->hasMany(TeamMember::class);
}

members relationship in Team model:

public function members()
{
    return $this->hasMany(TeamMember::class);
}

permissions relationship in TeamMember model:

public function permissions()
{
    return $this->belongsToMany(Permission::class);
}

But how can I optimise it? For example, to get all teams for users I need to use

Team::whereHas('teamMember', function($query) use ($user){
    $query->where('user_id', $user->id);
})->paginate();

But how can I implement a relationship that will contains all user's teams to get user's teams in one string of code, like $user->teams?

Upvotes: 0

Views: 117

Answers (1)

Deepesh Thapa
Deepesh Thapa

Reputation: 1789

I suggest you use many to many relation in regards to your team_members tables to explicitly mention as pivot.

User model:

public function teams()
{
    return $this->belongsToMany(Team::class, 'team_members');
}

Team model:

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

Since you want to use whereHas clause on teamMember table, I believe that you want to extract teams based on the fact that all teams belonging to that user based on team_members table.

So, You can specify the table name on many to many relation as above.

Now you can use

$user->teams

Upvotes: 1

Related Questions