【问题标题】:Spatie Laravel Permissions get users with permissionsSpatie Laravel Permissions 获取具有权限的用户
【发布时间】:2021-05-01 10:39:38
【问题描述】:

我试图弄清楚是否有一种简单的方法可以让所有具有给定权限的角色的用户。 所以我通过角色使用权限,这意味着我与他们没有直接关系,所以我需要检查用户模型“角色”的关系,然后检查与每个用户角色关联的权限。

带有数据集的SqlFiddle - http://sqlfiddle.com/#!9/2fe35d

任务是例如获取具有 id 2 和 3 权限的用户。

【问题讨论】:

  • sqlfiddle 很棒,但您还应该在此处提供示例表数据和预期结果,作为格式化文本(不是图像)。SO 问题应该是独立的。

标签: mysql sql laravel laravel-permission


【解决方案1】:

如果您只需要用户列表,您可以使用以下查询:

select distinct u.id , u.name username
from users u
join user_has_role ur
   on u.id = ur.user_id
join role_has_permissions rp
   on ur.role_id = rp.role_id
where  rp.permission_id in ( 2, 3) 

【讨论】:

    【解决方案2】:

    请检查以下查询,谢谢

    select U.id, U.name AS UserName, R.name AS RoleName,P.id As PermissionID, P.name AS PermissionName
    FROM users U 
    INNER JOIN user_has_role ur on U.id = ur.user_id
    INNER JOIN roles R on ur.role_id = R.id
    INNER JOIN role_has_permissions rp on R.id = rp.role_id
    INNER JOIN permissions P on rp.Permission_id = P.id
    WHERE P.id in (2,3)
    

    【讨论】:

      【解决方案3】:

      我没有在文档中找到它,但有一个 permission scope 应该为您提供直接或通过角色拥有权限的所有用户:

      public function scopePermission(Builder $query, $permissions): Builder
      

      你可以这样使用它:

      User::permission([2, 3])->get();
      

      【讨论】:

        【解决方案4】:

        Spatie 权限包使用 Laravel 原生授权功能,这意味着您可以访问authorization docs 中定义的许多功能。

        其中一个功能是can() 指令。您可以将权限名称传递给can(),它将根据检查返回truefalse。例如:

        @can('view posts')
        
        if (auth()->user()->can('view posts') { }
        
        if ($user->can('view posts') { }
        

        使用您的示例,如果您想查找所有具有您任何权限的users

        // Get the name of your permissions
        $permissions = Permission::whereIn('id', [2,3])->pluck('name')->toArray();
        
        // Filter users based on if they have any of the permissions
        $users = User::all()
            ->filter(function ($user) use ($permissions) {
                if ($user->can($permissions)) {
                    return $user;
                }
                return false;
            });
        

        或者,如果users 必须拥有所有权限:

        // Filter users based on if they have all of the permissions
        $users = User::all()
            ->filter(function ($user) use ($permissions) {
                foreach ($permissions as $permission) {
                    if (!$user->can($permission)) {
                        return false;
                    }
                }
        
                return $user;
            });
        

        在 Spatie 网站上查看 using permissions via roles 的文档。

        【讨论】:

          猜你喜欢
          • 2021-05-29
          • 2016-06-02
          • 2020-09-15
          • 1970-01-01
          • 2017-03-11
          • 2020-07-10
          • 1970-01-01
          • 2019-01-19
          • 1970-01-01
          相关资源
          最近更新 更多