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

Adcade's avatar

Many to many relationship with roles

I have the tables users, communities and community_user

community
    id
    ... (other columns)

user
    id
    ... (other columns)

community_user
    id
    community_id
    user_id
    role

I want to create relationships so an user can belong to many communities and have a different role on each one (admin, member, etc).

How should I define my models? Can a many-to-many relationship have a key?

0 likes
3 replies
Nakov's avatar
Nakov
Best Answer
Level 73

Yes, you can have an extra column in the intermediate table, so you have defined it correctly except the id field is unnecessary in the community_user table.

So the relationship can be setup as such:

// User.php

public function communities() 
{
   return $this->belongsToMany(Community::class)->withPivot('role');
}

// Community.php


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

Then in order to save in the DB you can call:

$user->communities()->attach($communityId, ['role' => $role]);

Don't know what type will your role be, either an enum or int. But I believe this is enough information to continue.

1 like
Snapey's avatar

Perhaps user has to have many CommunityRole (CommunityRole belongs to user) where CommunityRole model also belongs to Role (Role has many CommunityRole). Also CommunityRole belongs to Community

It might be possible to use role_id on the community_user table but I don't know how you would differentiate between them when for instance asking for user's communities.

edit: I changed my mind above. This will be different to the email you got

I'm assuming that roles are defined in a table.

Please or to participate in this conversation.