用户创建时出现MySQL错误-字段没有默认值

时间:2018-09-19 19:47:19

标签: mysql yii2 yii2-advanced-app

我正在尝试使用配置文件保存新创建的用户。我正在使用Yii2-dektrium。我更改了profile表中的字段。现在,当我尝试在保存用户之前保存配置文件时,出现错误,因为仍然没有用户。没关系。但是在这种情况下,我会收到此错误:

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    |       |
+-------------+--------------+------+-----+---------+-------+

0 个答案:

没有答案