Pagination with many to many relationships

只愿长相守 提交于 2021-01-24 07:20:24

问题


I have products, categories and category_product (pivot) tables in my database.

I want to return the category info and products with pagination in the same response.

I know I can use Product::with('categories')->pagination(20),

but I don't want to attach the category to each product.

What is the proper way to get products belong to a specific category?

I have tried that but I can't get the pagination with that:

$category = Category::where('slug', $slug)->first();
$products = $category->products()->paginate(20);
return response()->json([
    'category' => new CategoryResource($category),
    'products' => ProductResource::collection($products),
]);

Here is my ProductResource

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')),
];

回答1:


This looks like an issue with the way data is returned from the Collection.

The easiest solution is:

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



回答2:


You can try as below

$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),
]);

Hope this is what you are looking for.



来源:https://stackoverflow.com/questions/65763285/pagination-with-many-to-many-relationships

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!