控制器
<?php
namespace app\controllers;
use yii\web\Controller;
use yii\data\Pagination;
use app\models\Country;
class CountryController extends Controller{
public function actionIndex()
{
$query = Country::find();
$pagination = new Pagination([
'defaultPageSize' => 5,
'totalCount' => $query->count(),
]);
$countries = $query->orderBy('name')
->offset($pagination->offset)
->limit($pagination->limit)
->all();
return $this->render('index', [
'countries' => $countries,
'pagination' => $pagination,
]);
}
}
创建视图
<?phpuse yii\helpers\Html;
use yii\widgets\LinkPager;
?>
<h1>Countries</h1>
<ul>
<?php foreach ($countries as $country): ?>
<li>
<?= Html::encode("{$country->name} ({$country->code})") ?>:
<?= $country->population ?>
</li>
<?php endforeach; ?>
</ul>
<?= LinkPager::widget(['pagination' => $pagination]) ?>
显示首页尾页下一页
<?= LinkPager::widget(['pagination' => $pagination, 'nextPageLabel' => '下一页', 'prevPageLabel' => '上一页', 'firstPageLabel' => '首页', 'lastPageLabel' => '尾页',]); ?>
model层分页(上面是controller分页,两种分页是不一致的)
$pages= (new \yii\db\Query())
->select(["wechat","name","fans","number"])
->from('ht_weumber');
$count = $pages->count();
$pagination = new Pagination(['defaultPageSize' => 50 ,'totalCount' => $count]);
$pages = $pages->offset($pagination->offset)
->limit($pagination->limit)
->all();
$arr = array("pages"=>$pages,"pagination"=>$pagination);
return $arr;