【问题标题】:Laravel cast model values when using Resource使用资源时 Laravel 转换模型值
【发布时间】:2021-05-17 16:13:31
【问题描述】:

当使用资源 created_atupdated_at casting 返回模型时工作正常, 但是当我修改toArray() 函数时,转换不起作用!

在我的模型中:

protected $casts = [
    'created_at' => 'datetime:Y-m-d:h',
    'updated_at' => 'datetime:Y-m-d:h',
];

在资源中:

 public function toArray($request)
{
    return [
        'id' => $this->id,
        'name' => $this->name,
        'value' => $this->value,
        'box' =>  new BoxResource($this->box),
        'created_at' => $this->created_at,
        'updated_at' => $this->updated_at,
    ];
}

在控制器中:

  public function index(Request $request)
{

    return CurrencyResource::collection(
        Currency::where("user_id", "=", $request->user()->id)
          
            ->paginate($per_page)
    );
}

如何使铸造工作?

【问题讨论】:

    标签: laravel laravel-resource


    【解决方案1】:

    如果它不起作用,您的意思是时间戳恢复为碳实例?那你可以直接使用 format 方法。

    'created_at' => $this->created_at->format('Y-m-d:h'),
    'updated_at' => $this->updated_at->format('Y-m-d:h'),
    

    【讨论】:

    • 很好的答案,但有什么办法可以解决这个问题
    • 文档清楚地说明了使用$cast 进行日期转换的主题。 "模型序列化为数组或JSON时会使用这种格式:"
    猜你喜欢
    • 2020-03-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-20
    • 2016-12-30
    • 2018-01-16
    • 2021-09-20
    • 2022-10-30
    相关资源
    最近更新 更多