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,
));
}
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 ) ;