Defining an additional relation on a pivot table in laravel

Viewed 29

I'm working on a little laravel project, in which i have groups and users in a many-to-many relationship. These models use the following pivot table "group_members" :

+---------------+------------------+------+-----+---------+----------------+
| Field         | Type             | Null | Key | Default | Extra          |
+---------------+------------------+------+-----+---------+----------------+
| id            | int(10) unsigned | NO   | PRI | NULL    | auto_increment |
| group_id      | int(10) unsigned | NO   | MUL | NULL    |                |
| user_id       | int(10) unsigned | NO   | MUL | NULL    |                |
| group_role_id | int(10) unsigned | NO   | MUL | NULL    |                |
+---------------+------------------+------+-----+---------+----------------+

In this table i have added an additional id named "group_role_id", which is linked to the type of the membership (regular member, moderator, ...) in the "group_roles" table :

+-------------+------------------+------+-----+---------+----------------+
| Field       | Type             | Null | Key | Default | Extra          |
+-------------+------------------+------+-----+---------+----------------+
| id          | int(10) unsigned | NO   | PRI | NULL    | auto_increment |
| name        | varchar(255)     | NO   | UNI | NULL    |                |
| description | text             | YES  |     | NULL    |                |
+-------------+------------------+------+-----+---------+----------------+

In the Group model, i defined the relationship with the additional group_role_id :

 public function members()
{
    return $this->belongsToMany('App\User', 'group_members', 'group_id', 'user_id')->withPivot('group_role_id')->withTimestamps();
}

So running the following code :

@foreach($group->members as $user)
   <p>{{ $user->getFullName()}} - {{ $user->pivot->group_role_id}}</p>
@endforeach

results in getting all the users for that group, with the corresponding group_role_id :

John Doe - 1
Jane Doe - 3

My question is : how can i use these group_role_id's to get the corresponding name from the group_roles_table?I've added a new model namend 'GroupRole', but i have no idea how i should link it to the pivot table. I've read the documentation about 'Ternary relationships', but i'm not quite sure if this is the case here? Thanks in advance

0 Answers
Related