我正在编写一个代码,管理员可以通过该代码注册用户并为其分配角色。我设法提出了收集表单数据的代码,在数据库中注册用户,但是调用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()
public function signup()
{
if (!$this->validate()) {
return null;
}
$user = new Admin();
$user->username = $this->username;
$user->email = $this->email;
$user->setPassword($this->password);
$user->generateAuthKey();
$user->first_name = $this->first_name;
$user->last_name = $this->last_name;
$user->mobile = $this->mobile;
$user->station_id = $this->station_id;
if($user->save()) {
$p_key = $user->getPrimaryKey();
$r=new DbManager;
// $r->init();
if($this->role == 1) {
$role = 'courier';
$r->assign($role, $p_key); //(userId, role)
}
else if($this->role == 2) {
$role = 'tickets_officer';
$r->assign($role, $p_key); //(userId, role)
}
else if($this->role == 3) {
$role = 'supervisor';
$r->assign($role, $p_key); //(userId, role)
}
}
return $p_key;
}
我得到的错误是这样的:
PHP Notice – yii\base\ErrorException
Trying to get property of non-object
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。
答案 0 :(得分:2)
首先,您应该定义authManager
组件,而不是直接使用DbManager类。
assign()
的逻辑发生了变化。在最新版本中,它使用Role对象而不是string。
$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);