yii 如何将ActiveForm保存到数据库?为什么会出现“违反完整性约束”的情况?

0h4hbjxa  于 2022-11-09  发布在  其他
关注(0)|答案(1)|浏览(115)

我用Yii 2.0编写了这个测试应用程序。一个模型,一个表单。当我点击保存按钮时,我得到了错误:

Integrity constraint violation – yii\db\IntegrityException
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-〉保存()的行。为什么我的表单无法将数据保存到数据库?

SQL语言

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

文件db.php

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

文件测试.php

<?php
namespace app\models;
use yii\db\ActiveRecord;

class Test extends ActiveRecord {
    public $col1;
    public $col2;

    public static function tableName(){
        return 'test';
    }

    public function rules(){
        return [
            [['col1', 'col2'], 'required']
        ];
    }
}

文件测试.php

<?php

use yii\helpers\Html;
use yii\widgets\ActiveForm;

$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
        ]);
    }
bn31dyow

bn31dyow1#

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

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

如果要正确地执行此操作,请删除此操作,ActiveRecord将自动Map表中的列。

相关问题