使用Eloquent从与透视表相关的表中获取关系


Get relation from table related to pivot with Eloquent

因此,我得到了两个名为TeamUser的模型,其中User与多个Teams相关,而Team包含多个Users。这意味着我有一个名为team_user的数据透视表。

我想从用户那里获取团队成员。

我的关系设置如下:

// In the User model
public function teams()
{
    return $this->belongsToMany('App'Entities'Team');
}
// In the Team model
public function users()
{
    return $this->belongsToMany('App'Entities'User');
}

如何从用户返回团队中的用户?

我试过User::find(1)->teams()->users(),但不起作用。。

我正试图返回这样的数组:

 [
   'teamName' => 'Team #1',
   'users' => [
      [
         'username' => 'John Doe'
      ], [
         'username' => 'John Doe #2'
      ]
   ],
   'teamName' => 'Team #2',
   'users' => [
      [
         'username' => 'Doe John'
      ], [
         'username' => 'Doe John #2'
      ]
   ]

首先,如果数据透视表被称为team_user而不是team_users,则必须在关系中指定它:

// In the User model
public function teams()
{
    return $this->belongsToMany('App'Entities'Team', 'team_user');
}
// In the Team model
public function users()
{
    return $this->belongsToMany('App'Entities'User', 'team_user');
}

然后您可以通过访问用户的teams()->get()来检索团队,并添加with('users')来急切地加载每个团队的users关系:

$teams = User::find(1)->teams()->with('users')->get();