如何在 Yii2 Rbac 中更新 auth_assignment table 中的赋值?

How to update assignment in auth_assignment table in Yii2 Rbac?

我在我的 yii2 基本应用程序中使用 RBAC 来根据用户的角色将模块分配给他们。

我将角色 ID 和 user_id 存储在 auth_assignment table 中。

现在,如果我在更新期间更改用户角色。我还必须在 auth_assignment table 中更改它。现在我想从授权分配中删除该用户的所有条目并在 table.

中添加新条目

问题是我找不到任何 RBAC 函数来更新 auth_assignment table 数据或删除授权分配 table 数据。

Yii2 文档中有一个函数 removeAllAssignments() 但它截断了整个 table 我只想删除特定用户的条目。

有什么功能可以用吗?

是的,有。

assign() 将角色分配给用户。
revoke() 撤销用户的角色。
revokeAll() 撤销用户的所有角色。

要获取分配给用户的所有角色的列表,您可以使用 getRolesByUser()

假设角色名称是从表单发送的,并且您将值存储在 'role' 字段中,然后将其添加到您的模型中。

这将删除现有的分配,并分配新的分配。

public function afterSave($isInsert, $changedOldAttributes)
{

    // Update the user role in the RBAC layer
    // Purge the user tokens when the password is changed
    if (array_key_exists('role', $changedOldAttributes)) {

        $auth = Yii::$app->authManager;

        $auth->revokeAll($this->id );

        $role = $auth->getRole($this->role);

        $auth->assign($role, $this->id);
    }
        return parent::afterSave($isInsert, $changedOldAttributes);
    }