sersun
sersun

Reputation: 917

How do I structure this many-to-many-to-many relationship in the most "eloquent" way?

I can imagine a few ways to do this but I want to make sure I'm doing things efficiently and in a Laravel-optimized way.

I've got Users and Teams. Users can belong to many teams, and of course a team can have many users. A typical many-to-many:

class User extends Authenticatable
{
    public function teams()
    {
        return $this->belongsToMany('App\Team');
    }
}

and,

class Team extends Model
{
    public function users()
    {
        return $this->belongsToMany('App\User');
    }
}

I also want each user to have a "status" within each team. Eg, "Active" and "Inactive".

Do I create a third table/model for "Status", and set up pivots to both Users and Teams? If so, How do I use eloquent to efficiently fetch users of a given status for each team?

Is there a different approach I should consider?

Upvotes: 1

Views: 64

Answers (1)

Sanzeeb Aryal
Sanzeeb Aryal

Reputation: 3266

With many-to-many you obviously require an intermediate table. team_user be it. And you can add the status column to this table.

team_id    user_id    status
1          1          Active
2          1          Inactive
....

Relations:

public function teams()
{
    return $this->belongsToMany('App\Team')->withPivot('status');
}
public function users()
{
    return $this->belongsToMany('App\User')->withPivot('status');
}

And,

$users=User::with('teams')->get();
foreach($users as $user)
{
   foreach($user->teams as $team)
   {
        echo $team->pivot->status;
   }
}

Here is doc for Working with pivot tables

Upvotes: 3

Related Questions