Yii2.0实用功能技巧解密之——分页功能

十度 Yii2 2015年11月30日 收藏

Yii中的分页功能主要由yii\web: Linkable接口、yii\widgets: LinkPager类和yii\data: Pagination类三个组成。

  • yii\data: Pagination 主要功能是对分页中的参数进行设置,如当前页、每页大小、总页数,总记录数等。
  • yii\widgets: LinkPager 主要是根据yii\data: Pagination类所提供的参数生成前台页面的分页html代码。


使用:

先在action里面生成分页对象,然后在前台的LinkPager中使用。
后台controller中:

  1. function actionIndex()
  2. {
  3.         $query = Article::find()->where(['status' => 1]);
  4.         $countQuery = clone $query;
  5.         $pages = new Pagination(['totalCount' => $countQuery->count()]);
  6.         $models = $query->offset($pages->offset)
  7.           ->limit($pages->limit)
  8.           ->all();
  9.         return $this->render('index', [
  10.            'models' => $models,
  11.            'pages' => $pages,
  12.         ]);
  13. }


前台view中:

  1. foreach ($models as $model) {
  2.         // display $model here
  3. }
  4. // display pagination
  5. echo LinkPager::widget([
  6.         'pagination' => $pages,
  7. ]);


增强版

那如果要设置每页的大小或者再加排序怎么办?这个我已经对这个功能进行了封装
在基类控制器中添加:

  1. public function getPagedRows($query,$config=[])
  2. {
  3.         $countQuery = clone $query;
  4.         $pages=new Pagination(['totalCount' => $countQuery->count()]);
  5.         if(isset($config['pageSize']))
  6.         {
  7.                 $pages->setPageSize($config['pageSize'],true);
  8.         }
  9.         $rows = $query->offset($pages->offset)->limit($pages->limit);
  10.         if(isset($config['order']))
  11.         {
  12.                 $rows = $rows->orderBy($config['order']);
  13.         }
  14.         $rows = $rows->all();
  15.         $rowsLable='rows';
  16.         $pagesLable='pages';
  17.         if(isset($config['rows']))
  18.         {
  19.                 $rowsLable=$config['rows'];
  20.         }
  21.         if(isset($config['pages']))
  22.         {
  23.                 $pagesLable=$config['pages'];
  24.         }
  25.         $ret=[];
  26.         $ret[$rowsLable]=$rows;
  27.         $ret[$pagesLable]=$pages;
  28.         return $ret;
  29. }

其中$config参数有:

  • pageSize:设置每页的大小
  • order:数据的排序
  • rows:返回的数组中数据对象的键名
  • pages:返回的数组中分页对象的键名


后台使用如下:

  1. function actionIndex()
  2. {
  3.         $query = Article::find()->where(['status' => 1]);
  4.         //因为前台的数据对象为models,所以设置rows名称为models
  5.         $locals = $this->getPagedRows($query, ['order'=>'time desc', pageSize’=>5, 'rows'=>'models']);
  6.         return $this->render('index', $locals);
  7. }
是不是简单多了,而且由于这个功能实现在基类里面,所有的控制器都可以直接拿来用。