CodeIgniter4 日期自动更新 useTimestamps

在 CodeIgniter4 中,如果想要 Model 在创建及更新数据时自动更新对应的日期字段,可以使用 useTimestamps。但是有很多人会遇到遇到一些问题,其中最主要的问题是数据库字段与数据内容不匹配导致的。我们在设置了 $useTimestamps = true 后,往往忽略了与之配套使用的字段 dateFormat

一般的,我们在数据库中存储时间使用时间戳,我一般设置为 int UNSIGNED。大多人也是如此,在 CI4 中 dateFormat 的默认值为 datetime

1
2
3
4
5
6
7
8
9
case datetime:
$converted = $value->format(Y-m-d H:i:s);
break;
case date:
$converted = $value->format(Y-m-d);
break;
case int:
$converted = $value->getTimestamp();
break;

默认的日期格式为 2020-05-09 12:12:12 如果我们的数据会为 int 则数据会存储被为 2020 ,后边的信息无法存储。
所以我们需要将日期格式设置为 $dateFormat = int

Author

feng

Posted on

2020-05-09

Updated on

2024-03-14

Licensed under

Kommentare