当数据过多,无法一页显示时,我们经常会用到分页组件,YII2中已经帮我们封装好了分页组件。
首先我们创建操作数据表的AR模型:
<?php namespace app\models; use yii\db\ActiveRecord; class MyUser extends ActiveRecord
{
public static function tableName()
{
return '{{%user}}';
}
}
然后创建分页的控制器:
<?php namespace app\controllers; use YII;
use app\models\MyUser;
use yii\data\Pagination;
use yii\web\Controller; class IndexController extends Controller
{
public function actionIndex()
{
$name = YII::$app->request->get('name', '');
$where = '1=1 ';
$param = []; //如果查询条件很多,可以按这种方式,拼where条件
if (!empty($name)) {
$where .= "AND name=:name";
$param = array_merge($param, [':name' => $name]);
} //设置分页大小,为了演示,我写成了2
$pageSize = 2;
$user = MyUser::find()->where($where, $param); //创建分页组件
$page = new Pagination([
//总的记录条数
'totalCount' => $user->count(),
//分页大小
'pageSize' => $pageSize,
//设置地址栏当前页数参数名
'pageParam' => 'p',
//设置地址栏分页大小参数名
'pageSizeParam' => 'pageSize',
]); //获取数据
$data = $user->orderBy('id DESC')
->offset($page->offset)
->limit($page->limit)
->asArray()
->all(); return $this->renderPartial('index', [
'data' => $data,
'page' => $page,
]);
}
}
最后就是显示数据分页:
<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<title>分页显示</title>
<style>
.page li {
display: inline-block;
border: 1px solid #ccc;
border-radius: 3px;
padding: 2px 3px;
} .page li.active a {
font-weight: bold;
} .page li a {
text-decoration: none;
} .page li a, .page li span {
color: #666;
}
</style>
</head>
<body>
<ul>
<?php foreach ($data as $item): ?>
<li><?php echo $item['id']; ?> <?php echo $item['name']; ?></li>
<?php endforeach; ?>
</ul>
<?php
echo \yii\widgets\LinkPager::widget([
'pagination' => $page,
'firstPageLabel' => '首页',
'lastPageLabel' => '尾页',
'nextPageLabel' => '下一页',
'prevPageLabel' => '上一页',
//设置class样式
'options' => ['class' => 'page'],
]) ?>
</body>
</html>
最后效果如下: