Php Yii-自参考表
这是我的分类表Php Yii-自参考表,php,gridview,yii,zii-widgets,Php,Gridview,Yii,Zii Widgets,这是我的分类表 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', arr
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',
),
),
)); ?>
我必须对上述代码进行哪些更改。
谢谢
或者在调用中创建函数getCategoryName()并检索名称
'columns'=>array(
.....
array('name'=>'id','value'=>'$data->getCategoryName()'),
)
public function getCategoryName()
{
$equery= Category::model()->find("id=$this->id");
$cnm=$equery['Category'];
return $cnm;
}
或者在调用中创建函数getCategoryName()并检索名称
'columns'=>array(
.....
array('name'=>'id','value'=>'$data->getCategoryName()'),
)
public function getCategoryName()
{
$equery= Category::model()->find("id=$this->id");
$cnm=$equery['Category'];
return $cnm;
}
第一步-定义模型类中的关系:
public function relations()
{
return array(
'parent'=>array(self::BELONGS_TO, 'Category', 'parent_category_id'),
);
}
其中,Category
-是AR模型类的名称,parent\u Category\u id
-外键引用自身
步骤2-CGridView,列
属性:
...
'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。否则,您必须避免使用匿名函数第一步-在模型类中定义关系:
public function relations()
{
return array(
'parent'=>array(self::BELONGS_TO, 'Category', 'parent_category_id'),
);
}
其中,Category
-是AR模型类的名称,parent\u Category\u id
-外键引用自身
步骤2-CGridView,列
属性:
...
'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。否则,您必须避免使用匿名函数使用yii关系模型,然后在CGridView上使用“$data->Category->name”。使用yii关系模型,然后在CGridView上使用“$data->Category->name”。