如何在 Yii 中将日期设置为 NULL?

2022-01-04 00:00:00 validation datetime php mysql yii

我有一个日期列,通常将值设为 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;
} ...

也应该这样做.

相关文章