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

标签 laravel eloquent

我有 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/

相关文章:

mysql - 查找另一个表中未使用的名称

mysql - 将两个查询组合为单个 laravel

php - Laravel Eloquent 选择 1 :n to 1:1

php - Laravel 5.4 中非多形式/形式数据的单个文件上传

mysql - 如何获得相对于同一表中另一列的不同值的列的不同计数?

database - Laravel 不从数据库中检索双值

laravel - 使用 Laravel 的 Eloquent ORM 在 Slim 中出现 null 错误时调用成员函数 connection()

ruby - 为什么我在 Guard :watch in command line? 上收到 ruby​​ 错误

laravel - Laravel 中 pluck() 和 list() 的区别?

php - (2/2) ErrorException stdClass 类的对象无法在 laravel 5 中转换为 int