我只是不知道如何查询这些东西...我在集合中工作,但是代码很糟糕。
// user with roles
$user = User::where('id', Auth::User()->id)
->with('roles')
->first();
// Get the RoleParentId
$roleParentId = collect($user->roles)->min('parent_id');
// Get the all the children of the role parent Id with it's children and users
$role = \App\Model\Role::where('parent_id', $roleParentId)
->with('allChildren.users')
->first();
// Loop to get the Collection of children users
$childrenUsers = collect();
foreach($role->allChildren as $children){
$childrenUsers->push($children->users);
}
// Loop to get the Collection of user
$users = collect();
foreach($childrenUsers as $nCollect){
foreach($nCollect as $user){
$users->push($user);
}
}
return response()->json($users);
我的目标是让用户使用特定的parent_id ...我不知道如何查询它,所以我使用了集合,但我认为这不是一个好主意。 TY
答案 0 :(得分:1)
您可以使用whereHas
获得预期的结果。
$users = User::whereHas('roles', function() {
//Get the roles where the parent_id is the (minimum) parent_id from the user roles
return $query->where('parent_id', Auth::user()->roles()->orderBy('parent_id', 'ASC')->first()->parent_id);
});
更多信息,https://laravel.com/docs/5.7/eloquent-relationships#querying-relationship-existence