php - 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
{
}
解决方案
在模型中
首先,属性规则的方法称为“规则”我不知道是您在问题中的拼写错误还是这是问题所在;如果用户输入数据没有规则,则返回值将为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;
推荐阅读
- outlook - 服务器端 Outlook.Exchange 规则 执行脚本
- ruby-on-rails - Rails 部署到 heroku“检测 rails 配置失败”和“/usr/bin/env: 'ruby.exe\r': 没有这样的文件或目录”
- angular - Angular 7.2 HttpClient 删除方法不起作用,改为发送 Options 方法
- swift - 我试图在我的 ViewController 上显示两个 UICollectionViews,但是没有数据加载并且 UICollectionViews 是空的
- class - 使用函数或集合的数学符号描述类和类继承
- reinforcement-learning - 深度 q 学习 (dqn) 和神经拟合 q 迭代之间的区别
- python - 使用现有数据框的分组比率构建新数据框
- shell - 如何在 make 4.2 之前获取退出状态和 $(shell 命令) 的输出?
- javascript - Nest 无法解决依赖关系
- express - 为什么日期不显示在哈巴狗表单输入中?