【问题标题】:Laravel Eloquent Many-To-Many distinctLaravel Eloquent 多对多不同
【发布时间】:2016-02-22 05:45:08
【问题描述】:

我有一个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();

【问题讨论】:

  • 尝试添加return $this->hasManyThrough('App\Teams', 'App\Player')->distinct() 这应该检索用户所属所有球队的所有球员。但是,将 distinct 链接到 Eloquent 查询构建器的方法可能无法按预期工作。

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


【解决方案1】:

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

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

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

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-12-28
      • 2019-06-13
      • 2013-03-26
      • 1970-01-01
      • 2021-02-02
      • 2020-12-16
      • 1970-01-01
      相关资源
      最近更新 更多