laravel - 递归关系角色 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...我不知道如何查询它,所以我使用了该集合,但我认为这不是一个好主意。泰
解决方案
您可以使用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
推荐阅读
- c# - 正则表达式仅允许 C# 中的数字和逗号
- android - 使用机器学习套件从位图中读取条形码信息
- praat - “文本网格:缩放时间”功能用于将值从一个声音文件应用到现有的文本网格
- javascript - 如何在没有 Kibana 的情况下从 AWS 中的 ElasticSearch 访问数据?
- reactive-programming - 无法使用 cyclops-react 一致地运行并发订阅者
- node.js - package-lock.json 在 npm 5.6.0 中没用吗?我应该犯吗?
- regex - 正则表达式从字幕文件中删除空行和时间戳
- java - 如何使用 Selenium / Java 找到这个元素?
- vb.net - 检查表单的图标是否为空或设置为默认图标?
- css - 如何设置全局字体 - CSS