12

How to get users of a specefic role in Yii2 and DbManager in RBAC?

Please introduce some API for user management and role management.

I searched and read Yii2 guide but I didn't find any solution.

b24
  • 2,425
  • 6
  • 30
  • 51
  • 3
    The rbac\managerInterface does not provide an API for this. You will have to write your own, if you are using DbManager for your RBAC it is fairly straight forward, you can simply write a DB query. If you are using the PhpManager then it is little more complex as the filemanger stores the data in array like [user][role] so you will have to transpose the array first to get the data, or iterate over all users. – Manquer Aug 11 '14 at 16:54
  • Thanks man. I wrote a function based on your guide. – b24 Aug 22 '14 at 05:57

3 Answers3

9

Since Yii version 2.0.7, DbManager and ManagerInterface which it implements have getUserIdsByRole($roleName) which does what you want without custom code.

mmonem
  • 2,811
  • 2
  • 28
  • 38
  • 1
    With this block of code you can retrive user model by role: $operatoriIds = Yii::$app->authManager->getUserIdsByRole('operator'); $operators = User::find()->where(['id' => $operatoriIds])->all(); – Daniele Montes Dec 19 '16 at 10:06
  • This is a very clean solution and it worked for me. – Phemelo Khetho Mar 13 '21 at 19:50
5

I wrote this function which can be added to an User class.

 /**
 * Finds all users by assignment role
 *
 * @param  \yii\rbac\Role $role
 * @return static|null
 */
public static function findByRole($role)
{
    return static::find()
        ->join('LEFT JOIN','auth_assignment','auth_assignment.user_id = id')
        ->where(['auth_assignment.item_name' => $role->name])
        ->all();
}
Paul van Schayck
  • 517
  • 7
  • 10
4

I used @Manquer guide and wrote this function:

public static function getRoleUsers($role_name)
    {
        $connection = \Yii::$app->db;
        $connection->open();

        $command = $connection->createCommand(
            "SELECT * FROM auth_assignment INNER JOIN user ON auth_assignment.user_id = user.id " .
            "WHERE auth_assignment.item_name = '" . $role_name . "';");

        $users = $command->queryAll();
        $connection->close();

        return $users;
    }

Maybe useful for someone.

b24
  • 2,425
  • 6
  • 30
  • 51