How to make a ternary relationship in Laravel?

Asked

Viewed 1,209 times

0

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

I am doing a "multi client/company" application (type Basecamp) and the following relationship appeared:

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

Basically in the comic book would have to have a table with the keys:

user_id
permission_id
organization_id

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

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 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

2

Not directly answering 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 relationship.

The same goes for the relationship between permissions and entity, as you will need an intermediate table representing the many-to-many ratio.

What you probably need in this case is to focus on an architecture multi-tenant (multi-tenant) because your question is more related to architecture than the relation of entities in Laravel.

  • Your question does not solve the question problem.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.