Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

muuucho's avatar
Level 11

belongsToMany

I want to know how this relation works if I have alternative keys.

I like to write the relation "a team_user belongsToManyRoles" in Model TeamUser.php, but I don't know how. I try this:

public function roles()
    {
        return $this->belongsToMany(Role::class, 'role_team_user', 'role', 'team_user_id', 'id', 'name');
    }

This returns roles() empty while I expect data in it. Why?

0 likes
2 replies
muuucho's avatar
muuucho
OP
Best Answer
Level 11

Solution:

public function roles()
    {
        return $this->belongsToMany(Role::class, 'role_team_user', 'team_user_id', 'role', 'id', 'name');
    }
Maelfjord's avatar

@muuucho For future reference, parameters from the documentation are:

belongsToMany(TRelatedModel> $related, string|Model>|null $table = null, string|null $foreignPivotKey = null, string|null $relatedPivotKey = null, string|null $parentKey = null, string|null $relatedKey = null, string|null $relation = null)
1 like

Please or to participate in this conversation.