如何在Yii中将日期设置为NULL? [英] How can I set a date to NULL in Yii?

查看:151
本文介绍了如何在Yii中将日期设置为NULL?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个日期列,通常将值作为 dd.MM.yyyy 。它的模型的 rules()中的验证规则是:

 数组('start,end','date','format'=>'dd.MM.yyyy'),

我正在从CSV文件填充数据库,我希望能够将日期设置为 NULL (即没有),如果CSV记录是空的所以,我在做:

  if(empty($ csv_data)){
$ user-> start = new CDbExpression('NULL');
} else {
$ user-> start = $ csv_data;
}

但是我收到日期格式无效的错误。为什么会这样?



CDateValidator 文档说,默认情况下 allowEmpty 属性为true,因此应该可以将其设置为 NULL ,对吧?请注意,如果我只是将字符串加到日期,它将转换为 0000-00-00 00:00:00 timestamp,它不是 NULL

解决方案

p>在模型 rules()

  array('start, end','date','format'=>'dd.MM.yyyy'),
array('start,end','default','setOnEmpty'=> true,'value'= > null),

另外,



< p $ p> if(empty($ csv_data)){
$ user-> start = null;
} ...

也应该做的伎俩。


I have a date column that usually takes values as dd.MM.yyyy. Its validation rule in the model's rules() is this:

array('start, end', 'date', 'format' => 'dd.MM.yyyy'),

I'm populating the database from a CSV file, and I'd like to be able to set the date to NULL (i.e. nothing) if the CSV record is empty. So, I'm doing:

if (empty($csv_data)) {
  $user->start = new CDbExpression('NULL');
} else {
  $user->start = $csv_data;
}

But I get an error that the date format is invalid. Why is that?

The CDateValidator documentation says that the allowEmpty property is true by default, so it should be able to set this to NULL, right? Note that if I just assing the "" string to the date, it'll convert it to a 0000-00-00 00:00:00 timestamp, which is not NULL.

解决方案

in model rules():

array('start, end', 'date', 'format' => 'dd.MM.yyyy'),
array('start, end', 'default', 'setOnEmpty' => true, 'value' => null),

also,

if (empty($csv_data)) {
  $user->start = null;
} ...

should do the trick too.

这篇关于如何在Yii中将日期设置为NULL?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆