这是我的类别表
id category parent_category_id
1 animal NULL
2 vegetable NULL
3 mineral NULL
4 doggie 1
5 potato 2
6 hunting 4
我的yii网格视图显示父类别ID而不是名称。如何在网格视图中显示父类别名称。
<?php $this->widget('zii.widgets.grid.CGridView', array(
'id'=>'category-grid',
'dataProvider'=>$model->search(),
'filter'=>$model,
'columns'=>array(
'id',
'category',
'parent_category_id',
array(
'class'=>'CButtonColumn',
),
),
)); ?>
我必须在上面的代码中进行哪些更改。谢谢。
第一步-在模型类中定义关系:
public function relations()
{
return array(
'parent'=>array(self::BELONGS_TO, 'Category', 'parent_category_id'),
);
}
其中Category
-是AR模型类的名称,parent_category_id
-引用自身的外键。
第2步-CGridView,columns
属性:
...
'columns'=>array(
'id',
'category',
array(
'name'=>'Parent category', // col title
'value'=>function (Category $data){
if($data->parent_category_id)
return $data->parent->category; // "parent" - relation name, defined in "relations" method
return "-= root category =-";
}
),
)
...
注意:以上代码要求php版本> = 5.3。否则,您必须避免使用匿名函数
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句