Reputation: 99
Same story as many other questions on this site: I've banged my head into the wall for hours on end trying to figure out these relationships.
I have 3 models where the relationship should work like this:
Model: User
User can belong to many schools.
User belongs to one “Role” separately on each school.
User can be activated/deactivated separately on each school.
Model: School.
School can belong to many users
Model: Role.
Roles would be “Standard” or “Administrator”.
I have a pivot table that connects users and schools. On the pivot table, I've also experimented with adding 'role_id' and 'is_activated' columns - which I doubt is the correct way about doing this?
I want to access data like this:
User
Get schools belonging to the user.
Get role for current school.
Get activated/deactivated status for current school.
School
Get all users belonging to the school.
Get role for each user.
Get activated/deactived status for each user.
I would've solved this if users could only belong to one school each, but since the same user can belong to several schools it got too complicated for me.
What kind of relationships should I apply on each model?
I would very much appreciate if anyone can point me in the right direction here. Thanks!
Upvotes: 1
Views: 180
Reputation: 729
You can have a many-to-many
relationship between user
and school
. This would require a pivot table between them to store the ids of the two models. At the end your relationship from a user point of view will end up being:
public function schools() {
return $this->belongsToMany('App\Models\School', 'pivot_table', 'user_id', 'school_id');
}
You can have a look at laravel docs on Many-to-Many
Upvotes: 0