首页 文章

Yii框架创建时的日期时间格式无效

提问于
浏览
2

我有这样的 projects 表结构

CREATE TABLE IF NOT EXISTS `projects` (
  `project_id` int(11) NOT NULL AUTO_INCREMENT,
  `title` varchar(255) NOT NULL,
  `description` text NOT NULL,
  `url` varchar(255) NOT NULL,
  `create_time` datetime DEFAULT NULL,
  `create_user_id` int(11) DEFAULT NULL,
  `update_time` datetime DEFAULT NULL,
  `update_user_id` int(11) DEFAULT NULL,
  PRIMARY KEY (`project_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;

当我尝试用下一个表单创建新记录时

enter image description here

模型中的规则:

public function rules()
    {
        // NOTE: you should only define rules for those attributes that
        // will receive user inputs.
        return array(
            array('title, description, url', 'required'),
            array('create_user_id, update_user_id', 'numerical', 'integerOnly'=>true),
            array('title, url', 'length', 'max'=>255),
            array('create_time, update_time', 'safe'),
            // The following rule is used by search().
            // Please remove those attributes that should not be searched.
            array('project_id, title, description, url, create_time, create_user_id, update_time, update_user_id', 'safe', 'on'=>'search'),
        );
    }

我收到了错误

CDbCommand无法执行SQL语句:SQLSTATE [22007]:无效的日期时间格式:1292日期时间值不正确:''对于第1行的列'create_time' . 执行的SQL语句是:INSERT INTO项目( Headers ,描述,网址, create_time,create_user_id,update_time,update_user_id)VALUES(:yp0,:yp1,:yp2,:yp3,:yp4,:yp5,:yp6)

为什么?如何告诉Yii日期时间字段不是必需的,如果没有输入则可以包含默认值 .

3 回答

  • 4

    试试这个,因为这是Yii本身内部的自包含行为,它应该工作:

    在规则模型中添加:

    public function behaviors(){
            return array('CTimestampBehavior'=>array(
            'class' => 'zii.behaviors.CTimestampBehavior',
            'createAttribute' => 'create_time',
            'updateAttribute' => 'update_time',
            'setUpdateOnCreate' => true,  
            ));
        }
    
  • 1

    你点击按钮后可以尝试这样的东西创建它得到一些动作拿它举例如actionCreate()在actionCreate你喜欢如图所示

    public function actionCreate()
    {
    $model=new Project;
    if(isset($_POST['Project']))
    {
    $model->attributes=$_POST['Project'];
    $model->create_time=new CDbExpression('NOW()');
    $model->save(false);
    $this->redirect(array('view','id'=>$model->id));
    }
    $this->render('create',array(
    'model'=>$model,
    ));
    }
    
  • 0

    这不行吗?

    public function beforeSave()
    {
        if($this->isNewRecord)
        {
            $this->create_time=null;
            $this->update_time=null;
        }
        return parent::beforeSave();
    }
    

相关问题