因此,我得到了两个名为Team
、User
的模型,其中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();