分頁
1. 基于Laravel的ORM的分頁方式
Laravel的illuminate/database
提供了方便的分頁功能。
安裝
composer require illuminate/pagination
使用
public function index(Request $request)
{
$per_page = 10;
$users = Db::table('user')->paginate($per_page);
return view('index/index', ['users' => $users]);
}
分頁器實例方法
方法 | 描述 |
---|---|
$paginator->count() | 獲取當(dāng)前頁的數(shù)據(jù)總數(shù) |
$paginator->currentPage() | 獲取當(dāng)前頁碼 |
$paginator->firstItem() | 獲取結(jié)果集中第一個數(shù)據(jù)的編號 |
$paginator->getOptions() | 獲取分頁器選項 |
$paginator->getUrlRange($start, $end) | 創(chuàng)建指定頁數(shù)范圍的 URL |
$paginator->hasPages() | 是否有足夠多的數(shù)據(jù)來創(chuàng)建多個頁面 |
$paginator->hasMorePages() | 是否有更多的頁面可供展示 |
$paginator->items() | 獲取當(dāng)前頁的數(shù)據(jù)項 |
$paginator->lastItem() | 獲取結(jié)果集中最后一個數(shù)據(jù)的編號 |
$paginator->lastPage() | 獲取最后一頁的頁碼(在 simplePaginate 中不可用) |
$paginator->nextPageUrl() | 獲取下一頁的 URL |
$paginator->onFirstPage() | 當(dāng)前頁是否為第一頁 |
$paginator->perPage() | 獲取每一頁顯示的數(shù)量總數(shù) |
$paginator->previousPageUrl() | 獲取上一頁的 URL |
$paginator->total() | 獲取結(jié)果集中的數(shù)據(jù)總數(shù)(在 simplePaginate 中不可用) |
$paginator->url($page) | 獲取指定頁的 URL |
$paginator->getPageName() | 獲取用于儲存頁碼的查詢參數(shù)名 |
$paginator->setPageName($name) | 設(shè)置用于儲存頁碼的查詢參數(shù)名 |
注意
不支持$paginator->links()
方法
分頁組件
webman中無法使用 $paginator->links()
方法渲染分頁按鈕,不過我們可以使用其他組件來渲染,例如 jasongrimes/php-paginator
。
安裝
composer require "jasongrimes/paginator:~1.0"
后端
<?php
namespace app\controller;
use JasonGrimes\Paginator;
use support\Request;
use support\Db;
class UserController
{
public function get(Request $request)
{
$per_page = 10;
$current_page = $request->input('page', 1);
$users = Db::table('user')->paginate($per_page, '*', 'page', $current_page);
$paginator = new Paginator($users->total(), $per_page, $current_page, '/user/get?page=(:num)');
return view('user/get', ['users' => $users, 'paginator' => $paginator]);
}
}
模板(php原生)
新建模版 app/view/user/get.html
<html>
<head>
<!-- 內(nèi)置支持 Bootstrap 分頁樣式 -->
<link rel="stylesheet" >
</head>
<body>
<?= $paginator;?>
</body>
</html>
模板(twig)
新建模版 app/view/user/get.html
<html>
<head>
<!-- 內(nèi)置支持 Bootstrap 分頁樣式 -->
<link rel="stylesheet" >
</head>
<body>
{% autoescape false %}
{{paginator}}
{% endautoescape %}
</body>
</html>
模板(blade)
新建模版 app/view/user/get.blade.php
<html>
<head>
<!-- 內(nèi)置支持 Bootstrap 分頁樣式 -->
<link rel="stylesheet" >
</head>
<body>
{!! $paginator !!}
</body>
</html>
模板(thinkphp)
新建模版 app/view/user/get.html
<html>
<head>
<!-- 內(nèi)置支持 Bootstrap 分頁樣式 -->
<link rel="stylesheet" >
</head>
<body>
<?=$paginator?>
</body>
</html>
效果如下:
2. 基于Thinkphp的ORM的分頁方式
無須額外安裝類庫,只要安裝過think-orm即可
使用
public function index(Request $request)
{
$per_page = 10;
$users = Db::table('user')->paginate(['list_rows' => $per_page, 'page' => $request->get('page', 1), 'path' => $request->path()]);
return view('index/index', ['users' => $users]);
}
模板(thinkphp)
<html>
<head>
<!-- 內(nèi)置支持 Bootstrap 分頁樣式 -->
<link rel="stylesheet" >
</head>
<body>
{$users|raw}
</body>
</html>