How can I set a date to NULL in Yii?(如何在 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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何在 Yii 中将日期设置为 NULL?
基础教程推荐
- 学说 dbal querybuilder 作为准备好的语句 2022-01-01
- YouTube API v3 点赞视频,但计数器不增加 2022-01-01
- PHP PDO MySQL 查询 LIKE ->多个关键词 2021-01-01
- 在PHP中根据W3C规范Unicode 2022-01-01
- 如何替换eregi() 2022-01-01
- 如何在 Laravel 5.3 注册中添加动态下拉列表列? 2021-01-01
- Cron Jobs 调用带有变量的 PHP 脚本 2022-01-01
- 有什么方法可以用编码 UTF-8 而不是 Unicode 返回 PHP`json_encode`? 2021-01-01
- 如何在 Laravel 中使用 React Router? 2022-01-01
- PHP 类:全局变量作为类中的属性 2021-01-01
