Madriesen
Madriesen

Reputation: 619

add relationship to added values in pivot table laravel

I'm new to laravel relationships, but i'm familiar with SQL. I'm trying to add a pivot table with other values than just the two main ids.

I have some users, and some teams. Each user can play multiple instruments, and can be in multiple teams, but they can only play one instrument per team.

My pivot migration:

Schema::create('team_members', function (Blueprint $table) {

  $table->integer('user_id')->unsigned();
  $table->integer('team_id')->unsigned();
  $table->integer('instrument_id')->unsigned();

  $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
  $table->foreign('team_id')->references('id')->on('teams')->onDelete('cascade');
  $table->foreign('instrument_id')->references('id')->on('user_instruments')->onDelete('cascade');
});

I can already see this:

$team = Team::first();
$team->members->first()->details->instrument_id; // "2"

How can I define the relationship between instrument_id on user_instruments, so I can do $team->members->first()->details->instrument

UPDATE: I found this one: https://medium.com/@DarkGhostHunter/laravel-has-many-through-pivot-elegantly-958dd096db

Not sure if it will work...

Upvotes: 0

Views: 114

Answers (1)

Szaman
Szaman

Reputation: 2388

You should create an intermediate model TeamMember, in which you will define a relationship to Instrument. To achieve that, modify your many-to-many relationship on both Team and User, adding the option "using", like this:

// Team.php

public function members() {
  return $this->belongsToMany(App\User::class, 'team_members', 'user_id')
    ->using(App\TeamMember:class);
}

Then you need to create a model for your pivot table called TeamMember, which will extend the class Pivot and define the relationship with Instrument.

class TeamMember extends Pivot {
  public function instrument() {
    return $this->belongsTo(App\Instrument::class);
  }
}

Then you should be able to get the instrument like this (assuming you set a custom name for your pivot table as "details"): $team->members->first()->details->instrument.

Upvotes: 1

Related Questions