简体   繁体   中英

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

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.

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();
}

由于Yii的版本2.0.7, DbManagerManagerInterface它实现了具有getUserIdsByRole($roleName)这你想要做什么,而不自定义代码。

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM