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 that this table that will store the primary keys of the three tables is called links (just one example) and we have the models Users, Permissions, Organizations and Links.
When a relation n to n(Many to Many) it is necessary to have an intermediate table, which in this 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
So 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 recover all 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 other models' remaining relationships.
Note: I don’t have much experience in these more complex relationships, but this is what I understood from the period I met.
Documentation of the Laravel:
http://laravel.com/docs/eloquent#relationships
http://laravel.com/docs/eloquent#Working-with-pivot-Tables
Your question does not solve the question problem.
– Renan Rodrigues