Yii - Self Referencing Table

1.4k views Asked by At

This is my category table

id category  parent_category_id
1  animal      NULL
2  vegetable   NULL
3  mineral     NULL
4  doggie      1
5  potato      2
6  hunting     4

my yii grid view shows parent category id instead of name. how can i display the parent category name in grid view.

<?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',
        ),
    ),
)); ?>

what changes i have to make in the above code. thanks.

2

There are 2 answers

0
Ruslan Polutsygan On BEST ANSWER

First step - define relation in model class:

public function relations()
{
    return array(
        'parent'=>array(self::BELONGS_TO, 'Category', 'parent_category_id'),
    );
}

where Category - is name of AR model class, parent_category_id - foreign key referencing to itself.

Step 2 - CGridView, columns attribute:

...
'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 =-";


        }
    ),
)
...

Note: code above requires php version>=5.3. Otherwise you have to avoid using anonymous function

0
Kalpit On
'columns'=>array(
 .....
  array('name'=>'id','value'=>'$data->Category->name'),
 )

or create function inside call getCategoryName() and retreive name

'columns'=>array(
 .....
  array('name'=>'id','value'=>'$data->getCategoryName()'),
 )

 public function getCategoryName()
    {
       $equery= Category::model()->find("id=$this->id"); 
       $cnm=$equery['Category'];
       return $cnm;
    }