首页 > 解决方案 > 递归关系角色 Laravel 5.6

问题描述

我只是不知道如何查询这些东西......我在集合中工作,但它是非常糟糕的代码。

// 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...我不知道如何查询它,所以我使用了该集合,但我认为这不是一个好主意。泰

标签: laravelrecursion

解决方案


您可以使用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


推荐阅读