Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel belongsToMany pivot with multiple columns

Tags:

laravel

I currently have two tables in the DB and a pivot table to join them when I need to do a belongsToMany lookup. The basic example is one DB table is 'teams' and the other is 'members'. I can utilize the belongsToMany method on both the team and members model to pull their relationship with each other. A team can have many members, and a member can belong to many teams.

public function teams()
{
  return $this->belongsToMany(Team::class);
}

public function members()
{
  return $this->belongsToMany(Member::class);
}

Pivot: team_member
team_id  |  member_id
---------------------
   1     |      1
   2     |      1
   3     |      2
   1     |      2

How can I expand on that pivot table to include a type of member for each team? For example, member1 is a leader on team1. member1 is an assistant on team2. member1 is a generic member on team3... and so on. Can I just add a column to that same pivot table? Would it be the membertype_id? How can I relate that to another model/table?

like image 841
hiddenicon Avatar asked Dec 08 '22 15:12

hiddenicon


1 Answers

This is pretty common, and Laravel handles it already. Add extra columns to the pivot table and expand your relationships to use withPivot():

public function teams(){
  return $this->belongsToMany(Team::class)->withPivot(["teamRole", ...]);
}

Then accessing is as simple as:

$user = \App\User::with(["teams"])->first();
$team = $user->teams->first();
$teamRole = $team->pivot->teamRole;

See the Documentation for more information:

https://laravel.com/docs/5.6/eloquent-relationships

To answer the second part, which is essentially a "Triple Pivot", that requires extra functionality. See

Laravel - Pivot table for three models - how to insert related models?

for more information, and an associated Package (by the answerer on that question, not maintained, but good for an example)

https://github.com/jarektkaczyk/Eloquent-triple-pivot

like image 74
Tim Lewis Avatar answered Feb 06 '23 17:02

Tim Lewis