我有一个日期列,它通常将值作为 dd.MM.yyyy
。它在模型的 rules()
中的验证规则是这样的:
array('start, end', 'date', 'format' => 'dd.MM.yyyy'),
我正在从 CSV 文件填充数据库,如果 CSV 记录为空,我希望能够将日期设置为 NULL
(即什么都没有)。所以,我在做:
if (empty($csv_data)) {
$user->start = new CDbExpression('NULL');
} else {
$user->start = $csv_data;
}
但我收到日期格式无效的错误消息。这是为什么呢?
CDateValidator
documentation表示 allowEmpty
属性默认为 true,所以它应该能够将其设置为 NULL
,对吧?请注意,如果我只是将 ""
字符串赋值给日期,它会将其转换为 0000-00-00 00:00:00
时间戳,这不是NULL
.
最佳答案
在模型中rules()
:
array('start, end', 'date', 'format' => 'dd.MM.yyyy'),
array('start, end', 'default', 'setOnEmpty' => true, 'value' => null),
还有,
if (empty($csv_data)) {
$user->start = null;
} ...
也应该这样做。
关于php - 如何在 Yii 中将日期设置为 NULL?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14850081/