【问题标题】:Laravel: Resources with json fieldLaravel:带有 json 字段的资源
【发布时间】:2020-05-27 04:07:43
【问题描述】:

我在 Laravel 7.x 上,我有两个具有父子关系的模型(CustomerOrder 由许多 CustomerOrderLines 组成)。父 (CustomerOrder) 模型的字段中有一个 json 类型字段。

CustomerOrderResource.php:

return [
  'id' => $this->id,
  'wfx_oc_no' => $this->wfx_oc_no,
  'qty_json' => json_decode($this->qty_json)
];

CustomerOrderLineResource.php:

return [
  'id' => $this->id,
  'description' => $this->description,
  'customer-order' => $this->customerOrder
];

CustomerOrder->GET 请求返回格式正确的数据:

"data": {
    "id": 11,
    "wfx_oc_no": 12,
    "qty_json": {
        "L": "20",
        "M": "30",
        "S": "20",
        "XL": "100"
    }
}

但对于 CustomerOrderLine->GET,响应为:

"data": {
    "id": 15,
    "description": "test desc",
    "customer-order": {
        "id": 11,
        "wfx_oc_no": 12,
        "qty_json": "{\"L\": \"20\", \"M\": \"30\", \"S\": \"20\", \"XL\": \"100\"}"
    }
}

json 字段格式不正确。似乎它没有通过 Resource 类。请告诉我,我该如何解决这个问题?

仅供参考

CustomerOrderLine.php:

public function parent()
{
   return $this->belongsTo(CustomerOrder::class);
}

【问题讨论】:

    标签: json laravel laravel-resource


    【解决方案1】:

    终于设法使用json cast 解决了这个问题。该字段包含在模型中的$casts 数组中。

    【讨论】:

      猜你喜欢
      • 2019-03-29
      • 2021-11-03
      • 1970-01-01
      • 2019-12-08
      • 2020-05-09
      • 1970-01-01
      • 2023-03-16
      • 2017-09-16
      • 2020-06-13
      相关资源
      最近更新 更多