如何为非相关模型映射LaravelAPI资源

如何为非相关模型映射LaravelAPI资源,laravel,laravel-5,Laravel,Laravel 5,嗨,我正在创建不相关的模型资源。存货和类别。它们有子关系模型,但没有直接连接 样本: { "data": { "inventories": [ { "id": 1, "user_id": 1, "sub_category_id": 6, "created_at": "2019-03-08 03:00:00", "updated_at": "2019-03-08 03:00:00",

嗨,我正在创建不相关的模型资源。存货和类别。它们有子关系模型,但没有直接连接

样本:

{
  "data": {
    "inventories": [
      {
        "id": 1,
        "user_id": 1,
        "sub_category_id": 6,
        "created_at": "2019-03-08 03:00:00",
        "updated_at": "2019-03-08 03:00:00",
        "deleted_at": null,
        "get_inventory_details": {
          "id": 1,
          "inventory_id": 1,
          "image_path": "Pahiram-Drone1-1.png",
          "name": "Drone i1",
          "description": "Drone i1 The Best Drone yet!",
          "quantity": 10,
          "cost_per_day": 1000,
          "cost_per_hour": 100,
          "status": "0",
          "created_at": "2019-03-08 03:00:00",
          "updated_at": "2019-03-08 03:00:00",
          "deleted_at": null
        }
      }
    ],"categories": [
      {
        "id": 1,
        "category_id": 1,
        "parent_id": null,
        "created_at": "2019-03-08 03:00:00",
        "updated_at": "2019-03-08 03:00:00",
        "deleted_at": null,
        "get_sub_category_details": {
          "id": 1,
          "sub_category_id": 1,
          "category_type_id": 1,
          "name": "Drone DJI 1",
          "description": "Drone DJI 1",
          "created_at": "2019-03-08 03:34:23",
          "updated_at": "2019-03-08 03:34:23",
          "deleted_at": null
        }
      }
    ]
  }
}
这是我的样本数据

它与:

    public function toArray($request)
    {
        return parent::toArray($request);
    }
但不是:

     public function toArray($request)
     {
         return [
             'inventory_ids' => $this->inventories->id,
             'category_ids' => $this->categories->id
         ];
     }

我的预期结果是能够映射我的响应。

您不能从类别和清单中直接访问
id
,因为它是数组而不是对象

这应该对你有用

$categoryIds = Collection::make($this->categories)->pluck('id')->toArray();
$inventoryIds = Collection::make($this->inventories)->pluck('id')->toArray();


return [
  'category_ids' => $categoryIds,
  'inventory_ids' => $inventoryIds
];