gpt4 book ai didi

laravel - 具有多对多关系的分页

转载 作者:行者123 更新时间:2023-12-04 00:13:44 25 4
gpt4 key购买 nike

我有 products , categoriescategory_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')),
];

最佳答案

这看起来像 issue with the way data is returned从集合。
最简单的解决方案是:

return response()->json([
'category' => new CategoryResource($category),
'products' => ProductResource::collection($products)->response()->getData(true),
]);

关于laravel - 具有多对多关系的分页,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65763285/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com