如何将活动表单保存到数据库?为什么我会"Integrity constraint violation"?



我有这个用 Yii 2.0 编写的测试应用程序。一种模式,一种形式。 当我单击保存按钮时,出现错误:

Integrity constraint violation – yiidbIntegrityException
SQLSTATE[23000]: Integrity constraint violation: 19 NOT NULL constraint failed: test.col1
The SQL being executed was: INSERT INTO `test` DEFAULT VALUES
Error Info: Array
(
[0] => 23000
[1] => 19
[2] => NOT NULL constraint failed: test.col1
)
↵
Caused by: PDOException
SQLSTATE[23000]: Integrity constraint violation: 19 NOT NULL constraint failed: test.col1
in /home/bps/workspace/test/YiiTest/vendor/yiisoft/yii2/db/Command.php at line 963

符合 $model->save((。为什么我的表单无法将数据保存到数据库?

.sql

CREATE TABLE test(id INTEGER PRIMARY KEY, col1 VARCHAR(255) NOT NULL, col2 VARCHAR(255) NOT NULL UNIQUE);

文件数据库.php

<?php
return [
'class' => 'yiidbConnection',
'dsn' => 'sqlite:@app/sqlite3.db',
];

文件测试.php

<?php
namespace appmodels;
use yiidbActiveRecord;
class Test extends ActiveRecord {
public $col1;
public $col2;
public static function tableName(){
return 'test';
}
public function rules(){
return [
[['col1', 'col2'], 'required']
];
}
}

文件测试.php

<?php
use yiihelpersHtml;
use yiiwidgetsActiveForm;
$this->title = 'test';
?>
<div class="row">
<div class="col-lg-12">
<?php $form = ActiveForm::begin(); ?>
<?= $form->field($model, 'col1')->textInput(); ?>
<?= $form->field($model, 'col2')->textArea(); ?>
<?= Html::submitButton(); ?>
<?php ActiveForm::end(); ?>
</div>
</div>
<div class="row">
<div class="col-lg-12">
<div>record count: <?= $num_records ?></div>
<ul>
<?php foreach ($items as $item): ?>
<li><?= $item->col1 ?></li>
<?php endforeach; ?>
</ul>
</div>
</div>

站点控制器.php

public function actionTest(){
$model = new Test();
// add items
if (Yii::$app->request->isPost){
if ($model->load(Yii::$app->request->post()) && $model->validate()){
$model->save();
}
}
// schow items
$items = Test::find();
return $this->render('test', [
'num_records' => $items->count(),
'items' => $items->all(),
'model' => $model
]);
}

在模型中,您定义了属性:

class Test extends ActiveRecord {
public $col1;       // here
public $col2;       // and here

如果要正常工作,请将其删除,ActiveRecord 会自动映射表中的列。

相关内容

最新更新