I have a relation that I cant figure out my current application looks like this
Models
User.php public function teams() { return $this->belongsToMany(Team::class); }
Team.php public function tournaments() { return $this->belongsToMany(Tournament::class); }
Tournament.php public function teams() { return $this->belongsToMany(Team::class); }
Tables
tournaments id
teams id
team_tournament tournament_id team_id
Now a tournament can have just some of the users participate in the tournament so I’ve created the below
team_tournament_users tournament_id team_id user_id
To store users that are participating in a tournament from the team.
How should this look in terms of eloquent relations?
Advertisement
Answer
So taking your team_tournament_users, I would do the following
Would use the naming convention participants of tournament, so table name would be participants
instead of team_tournament_users
Migration
<?php use IlluminateSupportFacadesSchema; use IlluminateDatabaseSchemaBlueprint; use IlluminateDatabaseMigrationsMigration; class CreateParticipantsTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('participants', function (Blueprint $table) { $table->foreignId('tournament_id')->constrained(); $table->foreignId('user_id')->constrained(); $table->foreignId('team_id')->constrained(); $table->timestamps(); $table->primary(['tournament_id', 'user_id']); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('participants'); } }
Relationships: Then would define the following relationships in models
class User extends Model { public function teams() { return $this->belongsToMany(Team::class); } public function tournaments() { return $this->belongsToMany(Tournament::class, 'participants') ->withPivot('team_id') ->withTimestamps(); } } class Tournament extends Model { public function teams() { return $this->belongsToMany(Team::class); } public function participants() { return $this->belongsToMany(User::class, 'participants') ->withPivot('team_id') ->withTimestamps(); } } class Team extends Model { public function users() { return $this->belongsToMany(User::class)->withTimestamps(); } public function tournaments() { return $this->belongsToMany(Tournament::class)->withTimestamps(); } }
How would I then go about retrieving all the users participating in the team for a specific tournament? So if 3 users/members from a team are selected for the tournament how can I easily find out which members from that team are selected?
//There's already a relation between Tournament and Team(s) //So we can use it to get the tournament participants from the team $t = Tournament::with('participants')->first() ->participants ->groupBy(function($participant){ return $participant->pivot->team_id; }); //If Team with an id of 5 has members participating in the tournament //Then we can get the members of Team as $team = Team::findOrFail(5); $t->get($team->id);