【问题标题】:Dates not casting after upgrading to Laravel 7升级到 Laravel 7 后日期未转换
【发布时间】:2020-12-06 10:23:38
【问题描述】:

我刚刚从 Laravel 6 (PHP 7.4) 升级到 Laravel 7 (PHP 7.4),模型中的投射日期已经完全停止工作。

例如,在我的 User 模型中,我有以下 $dates 数组:

protected $dates = [
    'online_at'
];

返回以下内容:2020-08-17T00:00:00.000000Z 但我希望返回一个 Carbon 对象。

MySQL 数据库中的字段是 DATETIME。

created_atupdated_atdeleted_at 字段也是如此。所有型号也一样。

我尝试将字段移动到 $casts 数组中,但得到了相同的结果。

任何帮助将不胜感激。

【问题讨论】:

  • 这只发生在 API 上?
  • 刚刚测试过,是的,似乎是这样。

标签: php laravel php-carbon


【解决方案1】:

Laravel 7 在 Eloquent 模型上使用 toArraytoJson 方法时使用新的日期序列化格式。

以前,日期会被序列化为如下格式:

2019-12-02 20:01:00

使用 ISO-8601 格式序列化的日期将如下所示:

2019-12-02T20:01:00.283041Z

请注意,ISO-8601 日期始终以 UTC 表示。

如果您想继续使用以前的行为,您可以覆盖模型上的 serializeDate() 方法:

use DateTimeInterface;

protected function serializeDate(DateTimeInterface $date)
{
    return $date->format('Y-m-d H:i:s');
}

查看官方升级文档here

【讨论】:

    猜你喜欢
    • 2020-06-22
    • 2021-06-20
    • 2018-01-05
    • 2021-08-28
    • 1970-01-01
    • 2021-01-02
    • 2020-06-16
    • 2020-12-05
    • 1970-01-01
    相关资源
    最近更新 更多