如何将ActiveForm保存到数据库?为什么我会“违反诚信约束”?

时间:2017-08-22 16:24:17

标签: php yii yii2

我有这个用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-> save()。为什么我的表单无法将数据保存到数据库?

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',
];

文件Test.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']
        ];
    }
}

file test.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>

SiteController.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
        ]);
    }

1 个答案:

答案 0 :(得分:1)

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

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

如果你想正确地工作,删除它,ActiveRecord会自动映射你的表中的列。