douzhong5902 2019-08-08 17:22
浏览 92
已采纳

如何对关系数据进行分页LARAVEL [关闭]

I would like to know how I can paginate the called data of a relationship in Laravel, I do not want to load all the information in the same route, couse it would make the load heavier

I have categories and products, in the resource categories, I am calling the products through a relationship, but what I need to do is paginate those products

I need that in the route api/category/1, it returns the name of the category and the products on that specific category, (witch is working) but need those products paginated.

In my category controller:

 public function show($id)
{
    $category = Category::findOrFail($id);
    return new CategoryResource($category);
}

In my category model I have:

 public function products()
{
    return $this->hasMany('App\Product');
}

In my category resource I have:

 return [

        'name' => $this->name,
       //staff
        'products' => $this->products,
    ];

What I need to do is paginate that 'products' => $this->products, I already try 'products' => $this->products->paginate(5), but of course dont works, also try return $this->hasMany('App\Product'->paginate(5)); in my model but it also doesn't work.

Thank you in advance :)

  • 写回答

1条回答 默认 最新

  • douji3426 2019-08-08 17:42
    关注

    It was a syntax error, only one parenthesis was missing in: 'products' => $this->products()->paginate(5)

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 求差集那个函数有问题,有无佬可以解决
  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名
  • ¥65 汇编语言除法溢出问题