php - Yii - Self Referencing Table

513

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.

265

Answer

Solution:

First step - define relation in model class:

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

whereCategory - 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

557

Answer

Solution:

'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;
    }

People are also looking for solutions to the problem: php - phpmyadmin: Incorrect table rowcount with MySQL

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.