注册失败时分配用户角色,在Yii2中使用RBAC

注册失败时分配用户角色,在Yii2中使用RBAC,yii2,rbac,Yii2,Rbac,我正在编写一个代码,管理员负责注册用户并为他们分配角色。我已经设法找到了收集表单数据、在数据库中注册用户的代码,但是调用DbManager分配角色的最后一步失败了。我的代码如下所示 以下是actionCreate()函数: public function actionCreate() { $model = new Staff(); if ($model->load(Yii::$app->request->post()) && $model-&g

我正在编写一个代码,管理员负责注册用户并为他们分配角色。我已经设法找到了收集表单数据、在数据库中注册用户的代码,但是调用DbManager分配角色的最后一步失败了。我的代码如下所示

以下是
actionCreate()
函数:

public function actionCreate()
{
    $model = new Staff();

    if ($model->load(Yii::$app->request->post()) && $model->signup()) {
        return $this->redirect(['view', 'id' => $model->id]);
    } else {
        return $this->render('create', [
            'model' => $model,
        ]);
    }
}
下面是模型
Staff()

我得到的错误是:
PHP通知–yii\base\ErrorException

尝试获取非对象的属性

public function assign($role, $userId)
{
    $assignment = new Assignment([
        'userId' => $userId,
        'roleName' => $role->name,
        'createdAt' => time(),
    ]);

    $this->db->createCommand()
        ->insert($this->assignmentTable, [
            'user_id' => $assignment->userId,
            'item_name' => $assignment->roleName,
            'created_at' => $assignment->createdAt,
        ])->execute();
在上面的错误代码中,带有
'roleName'=>$role->name,
的行带有下划线,这意味着问题所在


请记住,我使用下拉菜单获取角色,其中选项为1、2或3。

首先,您应该定义
authManager
组件,而不是直接使用DbManager类

assign()
的逻辑已更改。在最新版本中,它采用角色对象而不是字符串

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

// You should previously init it once, e.c. in migration, like this: $auth->createRole('courier');
$courier = $auth->getRole('courier');
$auth->assign($courier, $p_key);

哇,太谢谢你了,伙计。你是一个伟大的救世主。就是这样。网上没有这样的文件。我想我一直在关注那些过时的文件。再次感谢。
$auth = Yii::$app->authManager;

// You should previously init it once, e.c. in migration, like this: $auth->createRole('courier');
$courier = $auth->getRole('courier');
$auth->assign($courier, $p_key);