paginate分頁及手動分頁(laravel)


Paginate分頁

//ORM  默認分頁
 $students=Student::paginate(5);
//顯示
$students->render();

// 使用簡單模板 - 只有 "上一頁" 或 "下一頁" 鏈接
Student::where('cars', 2)->simplePaginate(15);

// 手動分頁
$item  //手動查詢到的數據  
$total //所有符合條件的數據總數量  
$perPage      //每個頁面,數據顯示的條數
Paginator::make($items, $totalItems, $perPage);

手動分頁詳解
 laravel自帶的分頁功能十分強大,只不過,在使用 groupBy 語句的分頁操作時,無法由 Laravel 有效執行。如果你需要在一個分頁結果集中使用groupBy,建議你查詢數據庫並手動創建分頁器。

//控制器代碼    
    use Illuminate\Support\Facades\DB;
    use Illuminate\Pagination\LengthAwarePaginator;

    class IndexController extends Controller
    {
        //測試查詢數據庫並手動創建分頁器
        public function paginationTest(Request $request){
            $perPage = 5;
            $page = $request->input("page",1)-1;
            $total = DB::table("person")
                        ->groupBy()
                        ->count();
    
            $items = DB::table("person")
                        ->groupBy()
                        ->skip($page*$perPage)
                        ->take($perPage)
                        ->get();
            
            //$items = array_slice($users, ($current_page-1)*$perPage, $perPage);
            //5.4版本
            $person = new LengthAwarePaginator($items, $total,$perPage);
            //設置baseUrl的方法
            $person->withPath("pagTest");
            //5.4版本之前
             $paginator =new LengthAwarePaginator($items, $total, $perPage, $currentPage, [
            'path' => Paginator::resolveCurrentPath(), 
            'pageName' => 'page',
            ]);
    
            return view("index.paginationTest",['person' => $person]);
        }
    }

//blade
        普通分頁
{!!{ $paginator->render() }!!}
    攜帶查詢條件
{!! $paginator->appends(request()->input())->render() !!}    

底層詳解

        LengthAwarePaginator構造函數,代碼如下
    /**
     * Create a new paginator instance.
     *
     * @param  mixed $items
     * @param  int $total
     * @param  int $perPage
     * @param  int|null $currentPage
     * @param  array $options (path, query, fragment, pageName)
     * @return void
     */
    publicfunction __construct($items,$total,$perPage,$currentPage=null,array$options= [])
    {
        foreach ($optionsas$key=>$value) {
            $this->{$key} =$value;
        }
    
        $this->total=$total;
        $this->perPage=$perPage;
        $this->lastPage= (int)ceil($total/$perPage);
        $this->path=$this->path!='/'?rtrim($this->path,'/') :$this->path;
        $this->currentPage=$this->setCurrentPage($currentPage,$this->pageName);
        $this->items=$itemsinstanceofCollection ?$items: Collection::make($items);
    }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM