php - Yii - Self Referencing Table -
this 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 display 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 have make in above code. thanks.
first step - define relation in model class:
public function relations() { return array( 'parent'=>array(self::belongs_to, 'category', 'parent_category_id'), ); }
where category
- name of ar model class, parent_category_id
- foreign key referencing 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 have avoid using anonymous function
Comments
Post a Comment