How to get users of a specefic role in Yii2 and Db

2019-04-20 06:28发布

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.

标签: php yii yii2 rbac
3条回答
混吃等死
2楼-- · 2019-04-20 06:59

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.

查看更多
老娘就宠你
3楼-- · 2019-04-20 07:02

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();
}
查看更多
Luminary・发光体
4楼-- · 2019-04-20 07:08

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

查看更多
登录 后发表回答