如何在Laravel中创建预加载关系的分页

huangapple go评论61阅读模式
英文:

How to create pagination in eager loaded relationship in laravel

问题

I want the pagination to happen in eager loaded relation but when I am using it I am getting an error.
Method Illuminate\Database\Eloquent\Collection::links does not exist. This only happens when I use {{ $SubjectReport->reports->links() }} in views rather than that everything is working fine as when I remove this {{ $SubjectReport->reports->links() }} the page loads with the number set in paginate method.

这段内容描述了在视图中使用 {{ $SubjectReport->reports->links() }} 时出现了错误,错误信息为 "Method Illuminate\Database\Eloquent\Collection::links does not exist.",但在删除该代码后一切正常。

Here is my controller

这是我的控制器

$SubjectReport = Subject::with(['assessment.curriculumUnit',
    'reports' => function($q) {
    $q->orderBy('id','DESC')->paginate(2);
}])->where('id',2)->first();
 
return view('learner.assessment_reports',compact('SubjectReport'));

这是我的控制器代码,其中包含了使用 paginate 方法进行分页的逻辑。

Here is my view

这是我的视图


@foreach ($SubjectReport->reports as $key => $report)

@endforeach

{{ $SubjectReport->reports->links() }}

这是我的视图代码,其中包含了尝试使用 links() 方法进行分页链接的部分。

英文:

I want the pagination to happen in eager loaded relation but when I am using it I am getting an error.
Method Illuminate\Database\Eloquent\Collection::links does not exist. This only happens when I use {{ $SubjectReport->reports->links() }} in views rather than that everything is working fine as when I remove this {{ $SubjectReport->reports->links() }} the page loads with the number set in paginate method.

This is what I have tried so far

Here is my controller

$SubjectReport = Subject::with(['assesment.curriculumUnit',
    'reports' => function($q) {
    $q->orderBy('id','DESC')->paginate(2);
}])->where('id',2)->first();
 
return view('learner.assesment_reports',compact('SubjectReport'));

Here is my view


@foreach ($SubjectReport->reports as $key => $report)

@endforeach

{{ $SubjectReport->reports->links() }}

答案1

得分: 1

很遗憾,with 不正确地处理分页。它仅返回Collection中的部分数据,而不是Paginator
在关系分页的最佳方法是:

$SubjectReport = Subject::with('assesment.curriculumUnit')->where('id', 2)->first();
$SubjectReport->reports = $SubjectReport->reports()->orderBy('id', 'DESC')->paginate(2);
英文:

Unfortunately, with doesn't work with pagination correctly. It's return only portion of data in Collection instead Paginator.
The best way to paginate relation is:

$SubjectReport = Subject::with('assesment.curriculumUnit')->where('id',2)->first();
$SubjectReport->reports = $SubjectReport->reports()->orderBy('id','DESC')->paginate(2);

huangapple
  • 本文由 发表于 2023年5月29日 19:03:34
  • 转载请务必保留本文链接:https://go.coder-hub.com/76356785.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定