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

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

问题描述

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

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'),

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

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?

CDateValidator 文档allowEmpty 属性默认为 true,所以应该可以设置为 NULL 吧?请注意,如果我只是将 "" 字符串分配给日期,它会将其转换为 0000-00-00 00:00:00 时间戳,这不是NULL.

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():

in model rules():

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

还有,

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

也应该这样做.

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

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