在CGridView里,有时候需要用到复杂的查询时,可用 CSqlDataProvider替换CActiveDataProvider,
CSqlDataProvider 可用复杂的查询语句,例子如下:
1.在控制器中:
public function actionIndex() { $count = Yii::app()->db->createCommand(‘SELECT COUNT(*) FROM app_item‘)->queryScalar(); $sql = ‘SELECT * FROM app_item‘; $dataProvider = new CSqlDataProvider($sql, array( ‘totalItemCount‘ => $count,//数量 ‘sort‘ => array( ‘attributes‘ => array( ‘name‘=>array(‘label‘=>‘名称‘), ‘type‘=>array(‘label‘=>‘类型‘), ‘data‘=>array(‘label‘=>‘数据‘) ) ), ‘keyField‘=>‘name‘,//Yii 默认的主键是 id,而我的数据库默认的是 name,所以这里设定 name ‘pagination‘ => array( ‘pageSize‘ => 10 ), )); $this->render(‘index‘,array(‘dataProvider‘=>$dataProvider)); } //自定义函数,用于 type字段的解释 public function get_type($data,$row){ $type = $data["type"]; if( $type == 1 ) { echo ‘权限‘; }elseif( $type == 2 ) { echo ‘角色‘; }elseif( $type == 0 ) { echo ‘任务‘; } }
2.在视图中
$this->widget(‘zii.widgets.grid.CGridView‘, array( ‘id‘=>‘app-item-grid‘, ‘dataProvider‘=>$dataProvider, ‘columns‘=>array( array( ‘id‘=>‘CheckBox‘,//输出复选框 ‘class‘=>‘CCheckBoxColumn‘, ‘selectableRows‘ => ‘50‘, ), ‘name‘,//保持原样 array( ‘name‘=>‘type‘, ‘type‘=>‘raw‘, ‘value‘=>array($this,‘get_type‘), //get_type 是自定义的函数 ‘htmlOptions‘=>array(‘width‘=>"100px"), //设置样式 ), array( ‘header‘=>‘附加字段‘, ‘value‘=>‘substr($data["name"],0,3)‘,//如果是 CActiveDataProvider 时用对象方式 $data->name ), ), ))
3.结果如下
时间: 2024-10-10 13:59:18