1 year ago

belongsToMany with 4 tables

Posted 1 year ago by misterious

I have 4 tables with relations like on the picture ( https://i.stack.imgur.com/hitbj.png ) . I have also 2 functions in User model:

public function getUserSchools(){
    return $this->belongsToMany(Schools::class, 'user_has_schools', 'user_id', 'school_id');

public function getUserRoles(){
    return $this->belongsToMany(Roles::class, 'user_has_schools', 'user_id', 'role_id');

They work fine, but I want to merge results of them - I need to get schools of this user with his role in every school (for example: [Primary School, Teacher], [High School, Boss], etc.). How can I reach that result?

Please sign in or create an account to participate in this conversation.