Self Referencing Active Record

My database has a table called ‘tag’ that references itself. When I try to use $model->parent->name I get the error “Trying to get property of non-object”. Is there a problem with the way my relationships are defined? Any other ideas?

Here is my table setup:

tag_id

parent_id -->references tag_id

name

My Tags model has the following relationships defined:




	public function relations()

	{

		return array(

                        'parent' => array(self::BELONGS_TO, 'Tag', 'parent_id'), 

                        'children' => array(self::HAS_MANY, 'Tag', 'parent_id'), 

            

		);

	}



In my index file I am trying to loop through all tags to show their parent name using:




$data->parent->name;



That code yields the error "Trying to get property of non-object"

Here is my actionIndex:




	public function actionIndex()

	{

                $dataProvider=new CActiveDataProvider('Tag');

              

		$this->render('index',array(

			'dataProvider'=>$dataProvider,

		));

	}



Here is my index code:




 $this->widget('bootstrap.widgets.TbListView',array(

	'dataProvider'=>$dataProvider,

	'itemView'=>'_view',

)); 



Here is my _view code:




<div class="view">

	<b><?php echo CHtml::encode($data->getAttributeLabel('tag_id')); ?>:</b>

	<?php echo CHtml::link(CHtml::encode($data->tag_id),array('view','id'=>$data->tag_id)); ?>

	<br />

	<b><?php echo CHtml::encode($data->getAttributeLabel('parent_id')); ?>:</b>

	<?php echo $data->parent->name; ?>

	<br />

	<b><?php echo CHtml::encode($data->getAttributeLabel('name')); ?>:</b>

	<?php echo CHtml::encode($data->name); ?>

	<br />

</div>



Are you sure your referential ids exist? Are there parent and children? If there my not be, you need to check validity before you use an object. That just good programming.

If ( $data->parent ) doSomethingCool( $data->parent->name ) ;

Please go through this http://www.yiiframework.com/forum/index.php/topic/3127-ar-relations-with-a-self-referential-relation-type/

and

http://www.yiiframework.com/doc/guide/1.1/en/database.arr