Realtion in Pivot Table

Published 9 months ago by mdeorue

Hi guys,

I need your help, first sorry for my english, is too bad.

Well, I have 2 tables, teams and players, so I got a Many to Many relation, player_team, but in a team some players have different positions, like captain, etc... I made a column in player_team pivot table, that indicates the player position, captain, trainer, etc... And this column has a relation with player_positions.

I need that when I use belongsToMany relation I got the player_position relation eager load. So when I want the players of a team, I got there position too.

Thank you a lot for your help.

Dry7
Dry7
9 months ago (151,880 XP)

@mdeorue use

return $this->belongsToMany('App\Model')->withPivot('player_positions');
$user = App\User::find(1);

foreach ($user->roles as $role) {
    echo $role->pivot->player_positions;
}

If this does not help, then show your code

mdeorue

Hi, thanks for the reply, I actually do this, but the player_position is a related table to team_positions.

The team_positions table has... id | description

So I want to take this...

return $this->belongsToMany('App\Model')->withPivot('player_position')->with('position);

So for any team, I can take all the players and the position description in the team.

Thanks again.

Please sign in or create an account to participate in this conversation.