[英]Laravel Collection Pagination
我正在嘗試對集合進行分頁,但是我正在努力找出是否有更簡單的方法可以做到這一點。
我在AppServiceProvider
添加了以下宏:
Collection::macro('paginate', function($perPage) {
$page = request()->page ?: 0;
$slice = $this->chunk($perPage)[$page > 0 ? $page - 1 : 0];
return new LengthAwarePaginator($slice, $this->count(), $perPage, $page, [
'path' => url()->current(),
]);
});
這似乎暫時有效,但是我想知道從長遠來看是否會這樣做? 是否可以在結果成為集合之前對其進行分頁? 例如,這是我如何獲取要分頁的集合的方法:
在我的存儲庫中,我有:
private function eagerLoadQuotes()
{
return Quote::with([
'user',
'home',
'home.customer',
'installation',
'installation.commission',
'installation.preInstallationSurvey',
'installation.jobSheet'
]);
}
public function unstarted()
{
return $this->eagerLoadQuotes()->find(
Installation::doesntHave('preInstallationSurvey')
->pluck('quote_id')
);
}
private function mine($collection)
{
return $collection->filter(function ($item, $key) {
return $item->user_id == auth()->user()->id;
});
}
public function myUnstarted()
{
return $this->mine($this->unstarted());
}
然后我在控制器中得到它:
public function myUnstarted()
{
$quotes = $this->installations->myUnstarted();
return view('installations.viewAll', compact('quotes'));
}
還有許多其他方法可以重用私有方法。
有人創建了這個要點 ,我認為它將解決您的問題。
先前的答案將適用於Resultset集合,我想您是在詢問Illuminate\\Support\\Collection
。 如果是這種情況,請參考鏈接的Gist,內容如下:
$page = $page ?: (Paginator::resolveCurrentPage() ?: 1);
$items = $items instanceof Collection ? $items : Collection::make($items);
return new LengthAwarePaginator($items->forPage($page, $perPage), $items->count(), $perPage, $page, $options);
在您的控制器中。
在您的控制器中返回引號:
$quotes = Quote::with(['user', 'home', 'home.customer', 'installation', 'installation.commission', 'installation.preInstallationSurvey', 'installation.jobSheet'])
->find(Installation::doesntHave('preInstallationSurvey')->pluck('quote_id'))
->filter(function ($item, $key) {
return $item->user_id == auth()->user()->id;
}
)->paginate(10); // Number of results per page
然后在您看來:
{{ $quotes->links() }}
這只會查詢給定數量的每頁請求的行數,而不是返回所有引號實例,然后在其后對數組進行分塊。 將在大型館藏上提供更好的性能。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.