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:


parent_id -->references tag_id


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:


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

Here is my actionIndex:

	public function actionIndex()


                $dataProvider=new CActiveDataProvider('Tag');






Here is my index code:





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


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