ymike 2015-06-25 17:30:32 5554次浏览 2条回复 0 0 0

按照 http://www.yiichina.com/doc/guide/2.0/start-gii 的说明生成 CRUD 代码,但是在Create页面提交创建country操作数据库时报错。貌似模型country的值根本没有从前一个页面传递过来(INSERT INTO country (code) VALUES (NULL))。 之前按照 http://www.yiichina.com/doc/guide/2.0/start-databases 操作顺利。 用Navicat检查过了,确认数据库没有问题。 可能是什么原因?应该怎么检查? 谢谢!

Integrity constraint violation – yii\db\IntegrityException

SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'code' cannot be null
The SQL being executed was: INSERT INTO `country` (`code`) VALUES (NULL)
Error Info: Array
(
    [0] => 23000
    [1] => 1048
    [2] => Column 'code' cannot be null
)
↵
Caused by: PDOException

SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'code' cannot be null
  • 回复于 2015-06-26 07:29 举报

    代码贴出来看看!

  • 回复于 2015-06-26 17:10 举报

    用Model Generator重新生成country的代码后问题解决了。
    原来依照
    http://www.yiichina.com/doc/guide/2.0/start-databases
    已经手写的country的模型,再练习
    http://www.yiichina.com/doc/guide/2.0/start-gii
    时以为已经有country的模型,就用现成的,不用再生成了。

    问题就出在这里。看来是想当然害了我啊。
    书上得来终觉浅,绝知此事要躬行。
    不过这么折腾,学到了新东西,对yii的实际运行有了更深的认识。谢谢大家关注!

    原来出问题的代码如下:
    (依照http://www.yiichina.com/doc/guide/2.0/start-databases
    只是把namespace 从namespace app\models改成了frontend\models,因我用的advanced模板)

    <?php
    namespace frontend\models;
    use yii\db\ActiveRecord;
    class Country extends ActiveRecord
    {

    }

    可运行的新代码如下:

    <?php

    namespace frontend\models;

    use Yii;

    /**

    • This is the model class for table "country".
      *
    • @property string $code
    • @property string $name
    • @property integer $population
      /
      class Country extends \yii\db\ActiveRecord
      {
      /
      *

      • @inheritdoc
        */
        public static function tableName()
        {
        return 'country';
        }

      /**

      • @inheritdoc
        */
        public function rules()
        {
        return [
         [['code', 'name'], 'required'],
         [['population'], 'integer'],
         [['code'], 'string', 'max' => 2],
         [['name'], 'string', 'max' => 52]
        

        ];
        }

      /**

      • @inheritdoc
        */
        public function attributeLabels()
        {
        return [
         'code' => 'Code',
         'name' => 'Name',
         'population' => 'Population',
        

        ];
        }
        }

您需要登录后才可以回复。登录 | 立即注册