Search code examples
laravellaravel-5many-to-manydistinct

Laravel Eloquent Many-To-Many distinct


I have a Player Model which has many Teams and each Teams has many Player (Many-To-Many).

Player FooBar is a member of Team A and Team B. I would like to retrieve all the (distinct) players from Team A and B directly from my Player Model. Of course, each teams have many players, some similar, some different.

My player model example

class Player extends Model 
{
     teams(){

         return $this->hasMany('Teams');

     }

      teammates(){

           //Returns all the players from the teams where the player belongs

      }
}

What I would like to be able to do

$player = Player::find($id);

//Gets all the players from every team the player is playing with
$teammates = $user->teammates();

Solution

  • The "has-many-through" relationship provides a convenient short-cut for accessing distant relations via an intermediate relation. For example, a Country model might have many Post models through an intermediate User model. In this example, you could easily gather all blog posts for a given country

    I believe you should try using a hasManyThrough relationship, see Laravel Documentation on Has Many Through Relationships.

    $this->hasManyThrough('Teams', 'Player');