猿问

将其他数据传递给拉拉维尔资源

我需要将我的自定义数据传递到相同级别的资源数组,但它会脱离数组


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()),

                ]

            ]);


输出

米琪卡哇伊
浏览 113回答 2
2回答

不负相思意

由于“附加”用于顶级数据,因此请使用 instaed。concatreturn 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()),                ]            ]);

人到中年有点甜

您可以使用 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));
随时随地看视频慕课网APP
我要回答