分页与多对多关系 [英] Pagination with many to many relationships

查看:55
本文介绍了分页与多对多关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的数据库中有 products categories category_product (数据透视)表.

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.

我知道我可以使用 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),
]);

这是我的ProductResource

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

推荐答案

这看起来像最简单的解决方案是:

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

这篇关于分页与多对多关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆