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)

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

报告相同问题?

悬赏问题

  • ¥20 求快手直播间榜单匿名采集ID用户名简单能学会的
  • ¥15 DS18B20内部ADC模数转换器
  • ¥15 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历