Yii CGridView 之 SQL 语句
时间:2021-07-01 10:21:17
帮助过:4人阅读
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.结果如下
Yii CGridView 之 SQL 语句
标签: