【问题标题】:pass additional data to laravel resource将附加数据传递给 laravel 资源
【发布时间】:2020-02-11 19:51:41
【问题描述】:

我需要将我的自定义数据传递到同一级别的资源数组,但它超出了数组

return CategoryProductsResource::collection(Category::whereNull('parent_id')->get())
  ->additional([
                'data' => [
                    'id' => 9999,
                    'name' => 'How Offers',
                    'image' => 'http://businessdotkom.com/storage/categories/January2020/1o6nDi1kjVuwje5FiFXv.png',
                    'products' => ProductIndexResource::collection(Product::whereNotNull('sale_price')->get()),
                ]
            ]);

json output

【问题讨论】:

    标签: php json laravel api resources


    【解决方案1】:

    因为附加用于顶级数据,所以使用concat instaed。

    return CategoryProductsResource::collection(Category::whereNull('parent_id')->get())
      ->concat([
                    'data' => [
                        'id' => 9999,
                        'name' => 'How Offers',
                        'image' => 'http://businessdotkom.com/storage/categories/January2020/1o6nDi1kjVuwje5FiFXv.png',
                        'products' => ProductIndexResource::collection(Product::whereNotNull('sale_price')->get()),
                    ]
                ]);
    

    【讨论】:

      【解决方案2】:

      你可以使用 PHP array_merge() 函数

      $categories = Category::whereNull('parent_id')->get()->toArray();
      
      $merged = array_merge($categories, [
                 [
                   'id' => 9999,
                   'name' => 'How Offers',
                   'image' => 'http://businessdotkom.com/storage/categories/January2020/1o6nDi1kjVuwje5FiFXv.png',
                   'products' => ProductIndexResource::collection(Product::whereNotNull('sale_price')->get()),
                 ]
      ]);
      
      return CategoryProductsResource::collection(collect($merged));
      

      【讨论】:

      • 我收到错误调用整数成员函数 getKey()
      猜你喜欢
      • 1970-01-01
      • 2018-08-05
      • 1970-01-01
      • 2016-04-26
      • 2019-04-11
      • 1970-01-01
      • 2015-01-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多