In Laravel, relationships are treated in a very practical way, through the functions hasOne, hasMany, belongsTo, BelongsToMany, hasManyThrough, morphMany, morphToMany, and morphedByMany.
Let's say this table that will store the primary keys of the three tables if you call links (just an example) and have the models Users, Permissions, Organizations and Links.
When a relation n to n (many to many) is necessary that one has a table intermediate, that in the case is the links. Laravel (Eloquent ORM) has some facilities to interact with this table.
If the location of your models is in the default: app / models
Then in your model users we will create the relationship:
public function permissions()
{
return $this->belongsToMany('Permissions', 'Links');
}
public function organization()
{
return $this->belongsTo('Organizations', 'Links');
}
In the controller we can do the following:
$permissions = User::find($id)->with('permissions')->get();
or
$permissions = User::find($id)->permissions;
This will retrieve all the permissions of a user from all organizations, so you have to limit the selection to a specific organization.
$permissions = User::find($id)->with('permissions', 'organization')->where('links.organization_id', '=', $organization_id)->get();
or
$permissions = User::find($id)->with('permissions')->whereHas('organization',function($query) use ($organization_id)
{
$query->whereId($organization_id);
})->get();
Also create the remaining relationships of the other models.
Note: I do not have much experience in these more complex relationships, but this is what I understood since the period I knew laravel.
Laravel documentation:
link
link