How to make a ternary relationship in Laravel?

0

What is the best way to make a ternary relationship in Laravel?

I'm doing a "multi client / company" application (basecamp type) and the following relationship appeared:

  • a user has a (0 .. n) permissão in that organization, with users, permissions, and organizations being entities.

Basically the BD would have to have a table with the keys:

user_id
permission_id
organization_id

Now the problem is to know how I do it in Laravel.

    
asked by anonymous 03.07.2014 / 17:44

2 answers

2

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

    
19.07.2014 / 04:17
2

Not responding directly to your question, but complementing ...

In fact, a user can have multiple permissions and a permission can be used by multiple users, only then you already have a ternary relation.

The same holds true for the relationship between permissions and entity, since you will need an intermediate table representing the many-to-many relationship.

What you probably need in this case is to focus on a multi-tenant (multi-tenant) architecture because your question is more architecture-related than the entity relationship in Laravel.

    
25.07.2014 / 18:53