我的数据库中有 products
、categories
和 category_product
(透视)表。
我想在相同的响应中返回带有分页的类别信息和产品。
我知道我可以使用 Product::with('categories')->pagination(20)
,
但我不想将类别附加到每个产品。
让产品属于特定类别的正确方法是什么?
我已经试过了,但我无法获得分页:
$category = Category::where('slug', $slug)->first();
$products = $category->products()->paginate(20);
return response()->json([
'category' => new CategoryResource($category),
'products' => ProductResource::collection($products),
]);
这是我的产品资源
return [
'id' => $this->id,
'name' => $this->name,
'description' => $this->description,
'code' => $this->code,
'image' => $this->image,
'quantity' => $this->quantity,
'price' => $this->price,
'slug' => $this->slug,
'sort_order' => $this->sort_order,
'created_at' => $this->created_at,
'updated_at' => $this->updated_at,
'categories' => CategoryResource::collection($this->whenLoaded('categories')),
];
答案 0 :(得分:7)
这看起来像集合中的 issue with the way data is returned。
最简单的解决方案是:
return response()->json([
'category' => new CategoryResource($category),
'products' => ProductResource::collection($products)->response()->getData(true),
]);
答案 1 :(得分:0)
您可以尝试如下
$category = Category::where('slug', $slug)
->with('products', function($query) {
$query->paginate(20);
})
->first();
return response()->json([
'category' => new CategoryResource($category),
'products' => ProductResource::collection($category->products),
]);
希望这就是您要找的。p>