Laravel Spatie快速加载获取所有权限 [英] Laravel Spatie Get All Permissions with Eager Loading
问题描述
大家!我正在使用Laravel Spatie许可包.这样我就可以获得用户的所有分配的权限.
everybody! I am using Laravel Spatie Permission Package. And I can get user's all assigned permissions like this.
$user->getAllPermissions()
但是,我想通过急切的加载获得所有权限.也许是这样.
However, I want to get all permissions with eager loading. Maybe like this.
$users = User::with('getAllPermissions')->get();
但这没用.
我尝试了
$users = user::with('permissions')->get();
但是查询计数与
$users = user::get();
那么 $ user-> getAllPermissions()
已经渴望加载查询了吗?
So $user->getAllPermissions()
is already eager loaded query?
还是有急切需要加载的查询?
Or is there any eager loaded query?
推荐答案
要获得用户列表的所有权限,这是一件非常棘手的事情.
It is a pretty tricky thing to do to get all permission with user lists.
$users = user::with('permissions')->get();
这将为用户列表提供权限模型.这样,您将仅获得分配给用户的权限.但是用户具有角色,则不会添加角色权限.
this will provide permissions model with users list. In this way, you will get only permissions assigned to a user. But the user has a role then role permission will not be added.
但是 $ user-> getAllPermissions();
函数将为您提供与用户角色和权限相关的所有权限.但是我们需要用户列表的所有许可.
But $user->getAllPermissions();
function will give you all permission related to user role and permission. But we need all permission with the users' list.
我创建了一个Mutators函数来获取用户列表的权限.
I created a Mutators function to get permissions with the user list.
public function getPermissionAttribute()
{
return $this->getAllPermissions();
}
现在您可以在模型中添加
now You can append in your model
protected $appends = [
'permission'
]
现在要避免进行递归查询,请像这样编写用户查询
Now to avoid recursive query, write your user query like this
$users = user::with(['permissions', 'roles'])->get();
或添加您的用户模型
protected $with =[
'permissions',
'roles'
]
我认为这会对您有所帮助.
I think this will help you.
这篇关于Laravel Spatie快速加载获取所有权限的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!