首页 > 解决方案 > yii2 - SQLSTATE [23000]:完整性约束违规:1048

问题描述

我是 yii2 的新手,我正在尝试向数据库发送请求,但结果表明这些列不能为空,尽管通过 @var_dump 检查时我可以看到发送数据,这是怎么回事以及如何修理它

---> 控制器

 public function actionSignup()
{
    $model = new Signup();

    if (isset($_POST['Signup'])) {
        $model->attributes = Yii::$app->request->post('Signup');


        if ($model->validate()) {
            $model->signup();
            # code...
        }
    }

    return $this->render('signup', ['model'=>$model]);

---> 查看页面

<?php
use \yii\widgets\ActiveForm; 
?>
<?php
$form = ActiveForm::begin(['class'=>'form-horizontal']);
?>

<?= $form->field($model,'email')->textInput(['autofocus'=>true]) ?>

<?= $form->field($model,'password')->passwordInput() ?>

<div>
<button type="submit" class="btn primary-btn">Submit</button>
</div>
<?php
ActiveForm::end();
?>

---> 型号

class Signup extends Model
{
public $email;
public $password;

public function reles()
{
    return [

        [['email', 'password'], 'required'],
        ['email', 'email'],
        ['email', 'unique', 'targetClass'=>'app\models\User'],
        ['password', 'string', 'min'=>2,'max'=>10]
    ];
}

public function signup()
{
    $user = new User();
    $user->email = $this->email;
    $user->password = $this->password;
    return $user->save();
}

---> phpmyadmin 数据库

在此处输入图像描述

namespace app\models;

use yii\db\ActiveRecord;


class User extends ActiveRecord
{

}

--> var_dump在此处输入图像描述

--> sql在此处输入图像描述在此处输入图像描述 在此处输入图像描述

标签: phpyii2

解决方案


在模型中

首先,属性规则的方法称为规则我不知道是您在问题中的拼写错误还是这是问题所在;如果用户输入数据没有规则,则返回值将为NULL,我之前遇到过这个问题,我没有包含rules()方法(或者在你的情况下它的名称不正确)并且模型返回 null属性值。您的代码必须是:

public function rules()
{
    return [

        [['email', 'password'], 'required'],
        ['email', 'email'],
        ['email', 'unique', 'targetClass'=>'app\models\User'],
        ['password', 'string', 'min'=>2,'max'=>10]
    ];
}

技术说明:通常,或者根据我的理解,密码应该至少有8个字符而不是2 个字符,如果输入的密码只有 2 个字符,它可以在一秒钟内被暴力破解。

在控制器中

正如@Serghei Leonenco 的回答一样,Yii2 已经提供了一些用于处理post请求的功能,所以请坚持使用 Yii2 功能,它可以增强您的应用程序安全性

所以在 actionSignup() 方法中的代码应该是

public function actionSignup()
{
    $model = new Signup();

    // Loads the post request directly onto the model and validates it against the model rules() method
    if($model->load(Yii::$app->request->post()) && $model->validate){
            $model->signup();      
            // Model validated and saved successfully, IT OUGHT TO BE SAVED IN THE DATABASE AT THIS POINT
            // Here you can set a flash or redirect the user to another page  
    }

    return $this->render('signup', ['model'=>$model]);
}

在视图中

最后,在您的视图代码中,最好使用 Yii2 内部函数作为 Html 按钮

<?= Html::submitButton('Signup', ['class' => 'btn btn-primary']) ?>

当然不要忘记使用 yii\helpers\Html

use yii\helpers\Html;

推荐阅读