[英]laravel - pagination on collection
我正在嘗試處理 eloquent 系列。 獲得用戶 model 和文章 model 一對多關系。 一個用戶可以擁有多篇文章。 一篇文章屬於一個用戶。
這是我在 controller 中檢索特定字段用戶撰寫的文章的方式:
public function articles(User $user) {
if(empty($user)) $user = Auth::user();
$articles = $user->articles->paginate(10); //here comes collection
// passing results to view
return view('articles.index', compact('articles'))
->with('i', (request()->input('page', 1) - 1) * 10);
}
我找到了許多用於對集合結果進行分頁的解決方案。 我最喜歡的是這里: https://stackoverflow.com/a/56142421/14330487
我的代碼是一樣的。 現在在新項目上使用 laravel 9、php 8.1.3。 我在 AppServiceProvider boot() 方法中創建了 Collection::macro。
<?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Pagination\Paginator;
use Illuminate\Support\Collection;
class AppServiceProvider extends ServiceProvider
{
public function boot()
{
// builtin bootstrap views for pagination
Paginator::useBootstrapFive();
/**
* Paginate collection
*
* @param int $perPage
* @param int $total
* @param int $page
* @param string $pageName
* @return array
*/
Collection::macro('paginate', function ($perPage, $total = null, $page = null, $pageName = 'page') {
$page = $page ?: LengthAwarePaginator::resolveCurrentPage($pageName);
return new LengthAwarePaginator(
$this->forPage($page, $perPage),
$total ?: $this->count(),
$perPage,
$page,
[
'path' => LengthAwarePaginator::resolveCurrentPath(),
'pageName' => $pageName,
]
);
});
}
}
不知道為什么我的 VSC 向我顯示 forPage() 和 count() 方法未定義......我在運行我的應用程序時沒有遇到任何錯誤。 但也看不到任何結果。
路由、controller 和視圖都很好,當我用另一種方式顯示結果時,但我得到它的方式很糟糕。 使用 Collection::macro 要溫和得多。
我的 AppServiceProvider.php 文件行中有使用 Illuminate\Support\Collection 和 LengthAwarePaginator。
真的不知道為什么它不起作用。 也許它的 laravel 9 故障? 我發現的解決方案看起來像是為 laravel 8 制作的。
感謝幫助。
我用另一種方式做到了,沒有 AppServiceProvider,只是通過創建一個 Helper class。解決方案在這里找到: https://sam-ngu.medium.com/laravel-how-to-paginate-collection-8cb4b281bc55
我的第一次嘗試沒有成功,原因是方法文章參數默認值聲明。 應該看起來像:
public function articles(User $user = null) {}
forPage() 和 count() 方法的未知定義只是來自 VSC 的顯示錯誤。
兩種解決方案都可以正常工作。
現在只是考慮哪種嘗試更好。
第一項()
最后一項()
全部的()
鏈接()
例子
#控制器
$orders = DB::table('訂單')->分頁(15);
#看法
$訂單->firstItem();
$訂單->lastItem();
$訂單->總計();
$訂單->鏈接();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.