我正在尝试用配置文件保存新创建的用户。我正在使用 Yii2-dektrium
. 我把原稿改了 profile
table。现在,当我在保存用户之前尝试保存配置文件时,我得到一个错误,因为仍然没有用户。这没关系。但在这种情况下,我得到了一个错误:
SQLSTATE[HY000]: General error: 1364 Field 'first_name' doesn't have a default value
The SQL being executed was: INSERT INTO `profile` (`user_id`) VALUES (45)
代码行如下:
public function actionCreate()
{
/**@var Profile $profile */
$profile = new Profile();
/**@var User $user */
$user = \Yii::createObject([
'class' => User::class,
'scenario' => 'create',
]);
$event = $this->getUserEvent($user);
$this->performAjaxValidation($user);
$this->trigger(self::EVENT_BEFORE_CREATE, $event);
if ($profile->load(Yii::$app->request->post()) && $user->load(\Yii::$app->request->post())) {
$user->username = $user->email;
if($user->save()){
$user = User::findOne(['email' => $user->email]);
$profile->user_id = $user->id;
if($profile->save()){
$user->addRoles(Yii::$app->request->post('roles'));
\Yii::$app->getSession()->setFlash('success', \Yii::t('user', 'User has been created'));
$this->trigger(self::EVENT_AFTER_CREATE, $event);
return $this->redirect(['users']);
}
}
}
return $this->render('create', [
'account' => $user,
'profile' => $profile,
'regionList' => ArrayHelper::getModelsSelect2(new Region()),
]);
}
这是我的改变 Profile
模型规则:
public function rules()
{
return [
[['first_name', 'second_name', 'third_name', 'region_id', 'city_id', 'address', 'phone'], 'required'],
[['region_id', 'city_id'], 'integer'],
[['first_name', 'second_name', 'third_name', 'address', 'phone'], 'string', 'max' => 255],
];
}
在此之后,只创建用户记录。编辑我的表架构:
mysql> DESCRIBE `profile`;
+-------------+--------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------------+--------------+------+-----+---------+-------+
| user_id | int(11) | NO | PRI | NULL | |
| first_name | varchar(255) | NO | | NULL | |
| second_name | varchar(255) | NO | | NULL | |
| third_name | varchar(255) | NO | | NULL | |
| region_id | int(11) | YES | MUL | NULL | |
| city_id | int(11) | YES | MUL | NULL | |
| address | varchar(255) | NO | | NULL | |
| phone | int(11) | NO | | NULL | |
| image | varchar(255) | NO | | NULL | |
+-------------+--------------+------+-----+---------+-------+
暂无答案!
目前还没有任何答案,快来回答吧!