如何使用Yii實現分頁功能?

ADVERTISEMENT

如何使用Yii實現分頁功能?

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,

ADVERTISEMENT

'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;

ADVERTISEMENT

/*

* 統計功能: 統計每日的運費

*/

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',

ADVERTISEMENT

),

));

}

[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',

),

),

)); ?>

優點: 可以使用自帶的樣式; 缺點: 效率略低.

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持路飯。

本文地址:

ADVERTISEMENT