【问题标题】:Pagination with many to many relationships多对多关系的分页
【发布时间】:2021-01-20 07:15:06
【问题描述】:

我的数据库中有productscategoriescategory_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')),
];

【问题讨论】:

  • 你能附上你的ProductResource代码吗?
  • 我刚刚添加了。

标签: laravel eloquent


【解决方案1】:

这看起来像是集合中的issue with the way data is returned

最简单的解决方案是:

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

【讨论】:

    【解决方案2】:

    你可以尝试如下

    $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>

    【讨论】:

    • 非常感谢您的回复!我试过了,但没有分页。我在类别下获得了 2 个不同的产品属性。
    • 你是对的,这样我得到了 20 个元素,但没有 Paginator 类。但是用你的方式我得到了分页器,你怎么没有得到它? $products = $category->products()->paginate(20);
    • 实际上,如果我返回 $category->products()->paginate(20);但是当我将它作为数组元素添加到 json 响应时我无法得到它
    猜你喜欢
    • 2015-04-23
    • 2016-07-19
    • 2015-11-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-02
    相关资源
    最近更新 更多