我想从一些组中获取所有用户。然而,有些事情让我感到困惑。我写了一些有效的东西,但如果可能的话,我希望简化它。
$groups = Group::with('users')->whereIn('id',array(78,160))->get();
$users = new Collection;
foreach ($groups as $group) {
foreach ($group->users as $user) {
$users->add($user);
}
}
$u = $users->unique();
foreach ($u as $user) {
echo $user->name;
}
我试着在"with('users')"中进行区分,但没有像预期的那样奏效。我也试着从用户模型端获取,但没有成功:
$users = User::with(array('groups' => function($q){
$q->whereIn('id',array(78,160));
}))->get();
您很可能无法使用with
来完成此操作,因为它首先加载所有组,然后使用另一个查询来获取该组的所有用户。
答案是
$users = User::whereHas('groups', function($q){
$q->whereIn('id',array(78,160));
})->get();
或
$users = User::join('users_groups', 'users.id', '=', 'users_groups.user_id')->whereIn('users_groups.group_id', [78, 160])->get(['users.*']);