Laravel Eloquent多对多不同

时间:2016-02-21 21:21:41

标签: laravel laravel-5 many-to-many distinct

我有一个Player模型,其中包含许多Teams,每个Teams都有许多Player(多对多)。

玩家FooBar A队 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();

2 个答案:

答案 0 :(得分:2)

  

“has-many-through”关系为通过中间关系访问远程关系提供了方便的捷径。例如,Country模型可能通过中间User模型具有许多Post模型。在此示例中,您可以轻松收集给定国家/地区的所有博客帖子

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

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

答案 1 :(得分:0)

如果您有一个关联用户和团队的数据透视表。您可以创建一个模型,例如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();

此查询为您提供了播放器列表。