Php Laravel雄辩关系和透视表

Php Laravel雄辩关系和透视表,php,laravel,eloquent,relationship,Php,Laravel,Eloquent,Relationship,我正在试验一个有用户和团队的Laravel应用程序。这些表看起来有点像这样(简化): 用户 id* 团队 id* 团队用户 团队id* 用户id* 伊斯莱德 证实 如您所见,用户可以是多个团队的一部分,并且*他也可以被指定为给定团队的领导者。一个团队可以有多个领导者 用户模型具有以下关系: // Returns all the teams connected to the user and where the confirmed timestamp is set public f

我正在试验一个有用户和团队的Laravel应用程序。这些表看起来有点像这样(简化):

用户

  • id*
团队

  • id*
团队用户

  • 团队id*
  • 用户id*
  • 伊斯莱德
  • 证实
如您所见,用户可以是多个团队的一部分,并且*他也可以被指定为给定团队的领导者。一个团队可以有多个领导者

用户模型具有以下关系:

// Returns all the teams connected to the user and where the confirmed timestamp is set
public function teams()
{
    return $this->belongsToMany(Team::class)->wherePivot('confirmed', '!=', null);
}
// Returns all the teams where the user is appointed team leader
public function teamleaderTeams()
{
    return $this->belongsToMany(Team::class)->wherePivot('isLeader', '=', 1);
}
该小组有:

public function confirmedUsers()
{
    return $this->belongsToMany(User::class)->where('confirmed', '!=', null);
}
我需要返回用户作为团队负责人的所有用户的东西。因此,如果您不是团队负责人,结果当然是空的,但是如果您是,它应该返回您被任命为团队负责人的所有团队的所有用户

我试着四处打听,得到了一些建议,但并没有真正找到解决办法。 我确实有点明白我想要什么(我想)。所以。。。由于您可以通过teamleaderTeams()关系判断用户是哪个团队的团队负责人,因此我可以循环遍历每个团队,然后要求通过confirmedUsers()关系获取所有已确认的用户。但我只在控制器中完成了这一点,看起来很混乱

也就是说,这只会使浏览器崩溃(它似乎处于无限循环或其他状态,我真的不明白为什么)


不管怎么说,有人找到了一个很好的teamleaderUsers()关系的解决方案(这不是一个好名字),它返回给定用户是团队负责人的所有团队中的所有用户(满嘴都是)

首先,这里有一个输入错误:

$users->add($user);
应该是:

第二,我认为你的方法是好的。但是,如果性能成为您的问题,您可能希望编写一个自定义查询进行优化,而不是依赖于Laravel ORM


第三,您可以这样命名关系:
leadingTeams
而不是
teamleaderTeams
leadingUsers
而不是
teamleaderUsers
我认为现在是使用Pivot模型的好时机。可以通过扩展pivot类来定义pivot模型。此外,还可以在轴模型中定义关系。因此,如果pivot模型中有
用户
关系,则可以进行如下查询:

TeamUser::with('users')->where('isLeader', 1); // If the pivot model is called TeamUser
当然,您可以像往常一样排除特定用户:

TeamUser::with(['users' => function($query) {
    $query->where('id', '<>', 1); // If we want to exclude user with id 1
}])
->where('isLeader', 1);
请阅读更多关于它的信息,这是


祝你好运

这就是我要找的。非常感谢你!寻找类似答案的人;与在控制器中运行foreach不同,您还可以在视图中轻松映射。您可以执行类似于Auth::user()->teamleaderTeams->map->confirmedUsers的操作
TeamUser::with('users')->where('isLeader', 1); // If the pivot model is called TeamUser
TeamUser::with(['users' => function($query) {
    $query->where('id', '<>', 1); // If we want to exclude user with id 1
}])
->where('isLeader', 1);
public function teamLeaders()
{
    return $this->hasMany('users')->where('isLeader', 1);
}