英文:
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);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论