Yii中的分页功能主要由yii\web: Linkable接口、yii\widgets: LinkPager类和yii\data: Pagination类三个组成。
使用:
先在action里面生成分页对象,然后在前台的LinkPager中使用。
后台controller中:
- function actionIndex()
- {
- $query = Article::find()->where(['status' => 1]);
- $countQuery = clone $query;
- $pages = new Pagination(['totalCount' => $countQuery->count()]);
- $models = $query->offset($pages->offset)
- ->limit($pages->limit)
- ->all();
- return $this->render('index', [
- 'models' => $models,
- 'pages' => $pages,
- ]);
- }
前台view中:
- foreach ($models as $model) {
- // display $model here
- }
- // display pagination
- echo LinkPager::widget([
- 'pagination' => $pages,
- ]);
增强版
那如果要设置每页的大小或者再加排序怎么办?这个我已经对这个功能进行了封装
在基类控制器中添加:
- public function getPagedRows($query,$config=[])
- {
- $countQuery = clone $query;
- $pages=new Pagination(['totalCount' => $countQuery->count()]);
- if(isset($config['pageSize']))
- {
- $pages->setPageSize($config['pageSize'],true);
- }
- $rows = $query->offset($pages->offset)->limit($pages->limit);
- if(isset($config['order']))
- {
- $rows = $rows->orderBy($config['order']);
- }
- $rows = $rows->all();
- $rowsLable='rows';
- $pagesLable='pages';
- if(isset($config['rows']))
- {
- $rowsLable=$config['rows'];
- }
- if(isset($config['pages']))
- {
- $pagesLable=$config['pages'];
- }
- $ret=[];
- $ret[$rowsLable]=$rows;
- $ret[$pagesLable]=$pages;
- return $ret;
- }
其中$config参数有:
后台使用如下:
是不是简单多了,而且由于这个功能实现在基类里面,所有的控制器都可以直接拿来用。
- function actionIndex()
- {
- $query = Article::find()->where(['status' => 1]);
- //因为前台的数据对象为models,所以设置rows名称为models
- $locals = $this->getPagedRows($query, ['order'=>'time desc', ‘pageSize’=>5, 'rows'=>'models']);
- return $this->render('index', $locals);
- }