Relations to same table

Hello everybody,

I’m new in Yii. It is really a great framework, indeed. Actually, I would like to ask about the relations to same table. For example I have a table below


TABLE SPESIALIS

id_spesialis

nama_spesialis

parent_id_spesialis [i](reference to id_spesialis itself)[/i]

My challenge is I want to display parent name in CGridView. I tried with this one below but it didn’t work




<?php $this->widget('zii.widgets.grid.CGridView', array(

	'id'=>'spesialis-grid',

	'dataProvider'=>$model->search(),

	'filter'=>$model,

	'columns'=>array(

		'id_spesialis',

		'nama_spesialis',

		'parent_id_spesialis',

        array(

            'name'=>'parent_id_spesialis',

            'filter'=>CHtml::listData(Spesialis::model()->findAll(), 'id_spesialis', 'nama_spesialis'),

            'value'=>Spesialis::model()->findByPk($model->parent_id_spesialis)->nama_spesialis,

        ),

		array(

			'class'=>'CButtonColumn',

		),

	),

)); ?>



Should I define relations to solve this problem? But I think it will cost extra join.

Looking forward to your help.

Thanks in advance

Yes, a relation would help you here. Indeed it would create a JOIN, but your current solution would issue a separate query for every result row. So you’re surely better off with a JOIN. If you have defined relations, it becomes as easy as:


        array(

            'name'=>'Parent',

            'value'=>'$data->parent_spesialis->name',

            'type'=>'text',

        ),