Yii分页方法

来源:互联网 发布:梅林 访客网络设置 编辑:程序博客网 时间:2024/06/04 19:37

Yii2.0的分页方法有两种,

第一种是调用自带的分页组件,以及渲染组件,

第二则是半调用,仍然调用分页组件但可以自己渲染views页面

方法一:使用ActiveDataProvider 和 GridView

[php] view plain copy
  1. public function actionIndex(){  
  2.         $dataProvider = new ActiveDataProvider([  
  3.             'query' => ArticleClass::find(),  
  4.             'pagination' => [  
  5.                 'pagesize' => '2',  
  6.              ]  
  7.         ]);  
  8.         return $this->render('index', [  
  9.             'dataProvider' => $dataProvider,  
  10.         ]);  
  11. }  

只需要在action中添加pagination属性指明pagesize参数即可,view使用GridView,效果如下


方法二:控制器中引入分页类,并在views中引入分页渲染

controller中:

[php] view plain copy
  1. use yii\data\Pagination;  
  2.   
  3.   
  4. public function actionIndex(){  
  5.         $query = ArticleClass::find();  
  6.         $countQuery = clone $query;  
  7.         $pageSize = 2;  
  8.         $pages = new Pagination(['totalCount' => $countQuery->count(),'pageSize' => $pageSize]);  
  9.         $models = $query->offset($pages->offset)  
  10.             ->limit($pages->limit)  
  11.             ->all();  
  12.         return $this->render('index', [  
  13.             'models' => $models,  
  14.             'pages' => $pages,  
  15.         ]);  
  16. }  

view中:

[php] view plain copy
  1. use yii\widgets\LinkPager;  
  2.   
  3.   
  4. <?php  
  5.         //循环展示数据  
  6.         foreach ($models as $model) {  
  7.             echo "<li>".$model['class_name']."</li>";  
  8.         }  
  9. ?>  
  10.       
  11.     <?= LinkPager::widget([   
  12.         'pagination' => $pages,   
  13.         'nextPageLabel' => '下一页',   
  14.         'prevPageLabel' => '上一页',   
  15.         'firstPageLabel' => '首页',   
  16.         'lastPageLabel' => '尾页',  
  17.     ]); ?>
原创粉丝点击