【问题标题】:wahy change created at format in laravel api resource?为什么在 laravel api 资源中以格式创建更改?
【发布时间】:2021-10-30 01:47:51
【问题描述】:

我在 baseModel 中定义了创建格式,如下所示:

protected function serializeDate(DateTimeInterface $date): string
{
    return Carbon::instance($date)->toIso8601String();
}

但是当我使用 api 资源时,改变了 created_at 格式

这是 api 资源:

 public function toArray($request)
{
    return [
        'id' => $this->id,
        'last_status' => $this->lastStatus->status,
        'terminal' => [
            'provider' => $this->terminal_provider,
            'psp' => $this->terminal_psp,
        ],
        'account' => [
            'iban' => $this->account_iban,
        ],
        'count' => $this->count,
        'amount_settle' => $this->amount_settle,
        'amount_wage' => $this->amount_settle,
        'created_at' => $this->created_at,
        'statuses' => AggregateStatusResource::collection($this->whenLoaded('statuses')),
        'shaparak_files' => ShaparakFileResource::collection($this->whenLoaded('shaparakFiles')),
    ];
}

为什么要更改所有 api 资源的格式

【问题讨论】:

  • 你使用的是什么版本的 Laravel?和 ?请编辑您的问题并向我们展示您的通话方式toArray。
  • 下面的帖子回答了你的问题吗?
  • 是的,但不推荐使用“setToStringFormat”。有没有其他选择?

标签: php laravel lumen


【解决方案1】:

Resource 类中的 created_at 日期未使用 toIso8601String 进行转换,因为它不再使用模型的 toArray() 方法,该方法将调用 serializeDate()。

一种选择是更新您的Resource 以明确格式化created_at 日期:

'created_at' => $this->created_at->toIso8601String(),

【讨论】:

    猜你喜欢
    • 2020-04-17
    • 1970-01-01
    • 1970-01-01
    • 2018-10-02
    • 1970-01-01
    • 2019-08-23
    • 1970-01-01
    • 2010-09-29
    • 2019-11-25
    相关资源
    最近更新 更多