升级到 Laravel 7 后日期未投射 [英] Dates not casting after upgrading to Laravel 7
问题描述
我刚刚从 Laravel 6 (PHP 7.4) 升级到 Laravel 7 (PHP 7.4),但模型中的日期转换完全停止工作.
I have just upgraded from Laravel 6 (PHP 7.4) to Laravel 7 (PHP 7.4) and casting dates in a model has completely stopped working.
例如,在我的 User 模型中,我有以下 $dates
数组:
For example, in my User model, I have the following $dates
array:
protected $dates = [
'online_at'
];
返回以下内容:2020-08-17T00:00:00.000000Z
但我希望返回一个 Carbon 对象.
The following is returned: 2020-08-17T00:00:00.000000Z
yet I am expecting a Carbon object to be returned.
MySQL 数据库中的字段是 DATETIME.
The field in the MySQL database is DATETIME.
created_at
、updated_at
和 deleted_at
字段也是如此.所有型号都相同.
The same is happening with the created_at
, updated_at
, and deleted_at
fields. It's also the same across all models.
我尝试将字段移动到 $casts
数组中,但得到了相同的结果.
I have tried moving the field into the $casts
array but I get the same result.
任何帮助将不胜感激.
推荐答案
Laravel 7 在 Eloquent 模型上使用 toArray 或 toJson 方法时使用新的日期序列化格式.
Laravel 7 uses a new date serialization format when using the toArray or toJson method on Eloquent models.
以前,日期会被序列化为如下格式:
Previously, dates would be serialized to a format like the following :
2019-12-02 20:01:00
使用 ISO-8601 格式序列化的日期将显示为:
Dates serialized using the ISO-8601 format will appear like :
2019-12-02T20:01:00.283041Z
请注意,ISO-8601 日期始终以 UTC 表示.
Please note that ISO-8601 dates are always expressed in UTC.
如果您想继续使用以前的行为,您可以覆盖模型上的 serializeDate()
方法:
If you would like to keep using the previous behavior you can override the serializeDate()
method on your model :
use DateTimeInterface;
protected function serializeDate(DateTimeInterface $date)
{
return $date->format('Y-m-d H:i:s');
}
查看官方升级文档这里
这篇关于升级到 Laravel 7 后日期未投射的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!