我有一个大而困难的SQL查询。对我来说很好。控制器中有以下代码:
public function index(OpenRegDepDataReportInterface $openRegDepDataReport, Request $request): Renderable
{
$applications = $openRegDepDataReport->getReport($advertisers, $category);
return view('applications.index', compact('applications'));
}
因此,getReport
方法给出了DB::select('<here is my big diffecult SQL>')
的结果,众所周知,它是一个数组。
但正如你所看到的,我正试图把结果传递给一个视图。当然,我想在视图中调用$applications->links()
,比如eloquent
集合。哪一种方法是正确和快速的?
发布于 2019-12-16 14:55:17
若要在表中显示分页,必须调用select,然后调用分页方法。
主计长:
$test = DB::table('users')->select('id')->paginate(10);
考虑到:
$test->links();
发布于 2019-11-09 15:21:48
简单答案,使用paginate()
方法:
$basicQuery = DB::select(DB::raw("<here is the big diffcult SQL query>"));
但是,paginate()
只对集合起作用,而且由于您有一个对象数组,所以需要首先使用forPage()
方法将其转换为集合:
forPage方法返回一个新集合,其中包含将出现在给定页码上的项。该方法接受页码作为其第一个参数,并接受每页显示的项目数作为其第二个参数:
$collection = collect($basicQuery);
$chunk = $collection->forPage(2, 3);
$chunk->all();
复杂的答案:自己构建一个分页器实例:
$perPage = 10;
$page = $request->input("page", 1);
$skip = $page * $perPage;
if($take < 1) { $take = 1; }
if($skip < 0) { $skip = 0; }
$basicQuery = DB::select(DB::raw("<here is the big diffcult SQL query>"));
$totalCount = $basicQuery->count();
$results = $basicQuery
->take($perPage)
->skip($skip)
->get();
$paginator = new \Illuminate\Pagination\LengthAwarePaginator($results, $totalCount, $take, $page);
return $paginator;
我建议使用paginate()
方法。
您可以阅读更多关于拉勒维尔(氏)分页的内容。
发布于 2019-11-09 15:21:51
因此,如果您的$applications
返回查询生成器结果,则根据文档,只需将->paginate(10);
追加到其中即可。
https://laravel.com/docs/master/pagination#paginating-query-builder-results
$applications = $openRegDepDataReport->getReport($advertisers, $category)->paginate(10);
https://stackoverflow.com/questions/58780512
复制相似问题