Yii实现分页的两种方法,一种是用DAO实现,另外一种是在widget实现.
各有优点吧,第一种效率会高一点, 第二种可以使用自带的表格,方便一些.
一. DAO实现分页.
[Controller层]
public function actionReport() { $sql = "select remitdate, sum(rate) sumrate from td_delivery group by remitdate order by remitdate desc"; $criteria=new CDbCriteria(); $result = Yii::app()->db->createCommand($sql)->query(); $pages=new CPagination($result->rowCount); $pages->pageSize=2; $pages->applyLimit($criteria); $result=Yii::app()->db->createCommand($sql." LIMIT :offset,:limit"); $result->bindValue(':offset', $pages->currentPage*$pages->pageSize); $result->bindValue(':limit', $pages->pageSize); $posts=$result->query(); $this->render('report',array( 'posts'=>$posts, 'pages'=>$pages, )); }
[View层]
<?php foreach($posts as $row):?> <?php echo CHtml::link($row["remitdate"],array('delivery/view','remitdate'=>$row["sumrate"]));?> <?php echo $row["sumrate"]."<br />" ?> <?php endforeach;?> <?php //分页widget代码: $this->widget('CLinkPager',array('pages'=>$pages)); ?>
优点: DAO效率高; 缺点: view层需要自己写一些样式,稍显麻烦一点
二. widget实现分页
[model层]
/** * @var string attribute : 日运费 (统计用) * 需要对新增加的字段做个声明 */ public $dayrate; /* * 统计功能: 统计每日的运费 */ public function statistics() { $criteria = new CDbCriteria; $criteria->select = 'remitdate, sum(rate) AS dayrate'; $criteria->group = 'remitdate'; return new CActiveDataProvider(get_class($this), array( 'criteria'=>$criteria, 'sort'=>array( // 表头设置点击排序的字段 'attributes'=>array( 'remitdate', 'dayrate'=>array( 'asc'=>'dayrate', 'desc'=>'dayrate DESC', ) ), 'defaultOrder'=>'remitdate desc', ), )); }
[Controller层]
/** * 运单统计功能: * 按日期统计 */ public function actionReport() { $model=new Delivery('statistics'); $model->unsetAttributes(); // clear any default values $this->render('report',array( 'model'=>$model, )); }
[View层]
<?php $this->widget('zii.widgets.grid.CGridView', array( 'id'=>'delivery-grid', 'dataProvider'=>$model->statistics(), 'filter'=>$model, 'columns'=>array( 'remitdate', 'dayrate', array( 'class'=>'CButtonColumn', ), ), )); ?>
优点: 可以使用自带的样式; 缺点: 效率略低.
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。