Laravel Eloquent 多对多不同

Laravel Eloquent Many-To-Many distinct

我有一个 Player 模型,其中有很多 Teams,每个 Teams 有很多 Player(多对多)。

玩家 FooBarA 队B 队 的成员。 我想直接从我的 Player 模型中检索 A 队和 B 队的所有(不同)球员。当然,每支球队都有很多球员,有的相似,有的不同。

我的播放器模型示例

class Player extends Model 
{
     teams(){

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

     }

      teammates(){

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

      }
}

我希望能够做什么

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

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

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

我相信您应该尝试使用 hasManyThrough 关系,请参阅 Laravel Documentation on Has Many Through Relationships

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

如果您有一个连接用户和团队的枢轴 table。您可以创建一个模型,例如 TeamUser:

class TeamUser extends Model {

protected $table = 'team_user';

  public function users()
  {
     return $this->belongsTo('App\Models\User');
  }

   public function teams()
  {
     return $this->belongsTo('App\Models\Team');
  }

}

那你可以试试这个:

$user = User::find($id);
$teams = $user->teams()->lists('id');
$players = UserTeam::with('users')->whereIn('team_id', $teams)->get();

此查询为您提供玩家列表。