我有一个用户模型和一个团队模型,一个团队中可以有很多用户(属于Torel的关系)。现在,我需要从已登录用户所属的团队中提取所有用户的列表。
我目前有以下代码:
$teams = $user->teams()->get()->pluck('id')->toArray();
return Team::whereIn('id', $teams)->with(['users'])->get()->map(function ($item) {
return $item->users->map(function ($user) {
return [
'name' => $user->name,
'email' => $user->email,
];
});
});
上面返回一个集合,如下所示:
Collection {#375 ▼
#items: array:2 [▼
0 => array:3 [▼
0 => array:2 [▼
"name" => "John Doe",
"email" => "john.doe@mail.com"
]
1 => array:2 [▼
"name" => "Jane Doe",
"email" => "jane.doe@mail.com"
]
2 => array:2 [▶]
]
1 => array:2 [▼
0 => array:2 [▼
"name" => "Jane Doe"
"email" => "jane.doe@mail.com"
]
1 => array:2 [▼
"name" => "John Doe",
"email" => "john.doe@mail.com"
]
]
]
}
这是一个更好的视图:
[
[
{
"name": "John Doe",
"email": "john.doe@mail.com"
},
{
"name": "Jane Doe",
"email": "jane.doe@mail.com"
},
{
"name": "John Doe",
"email": "john.doe@mail.com"
}
],
[
{
"name": "Jane Doe",
"email": "jane.doe@mail.com"
},
{
"name": "John Doe",
"email": "john.doe@mail.com"
}
]
]
如您所见,我有重复项,我需要删除这些重复项。我尝试使用独特和独特的方法而没有成功。
答案 0 :(得分:0)
我通过使用foreach循环部分解决了该问题,但是如果我能使用雄辩的查询来获取此数据,则更愿意。
$userArray = array();
foreach ($users as $user) {
if (array($user)) {
foreach ($user as $u) {
$userArray[] = $u['email'];
}
} else {
$userArray[] = $user['email'];
}
}
return array_unique($userArray);