Cactivedataprovider With Relations Trying To Get Property Of Non-Object

Hi, newbie on Yii. Basically, trying to figure out how to display the related field on another table.

Model:

  1. Users (relations)

'recipients' => array(self::HAS_MANY, 'Recipients', 'user_id'),

  1. Recipients (relations)

'users' => array(self::BELONGS_TO, 'Users', 'id'),

Controller (Action: Recipients/index):


public function actionIndex()

{

	$dataProvider=new CActiveDataProvider('Recipients', array(

		'criteria' => array(

			'with' => array('users')

		)

	));


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

		'dataProvider'=>$dataProvider,

	));

}

View:


<?php

echo CHtml::encode($data->user_id); // Default, works!

echo CHtml::encode($data->users->getAttribute('name')); // Works, can retrieve users->name but template breaks

print_r($data->users->getAttributes()); // Works, can retrieve array of users but template breaks

echo $data->users->username; // Error, Trying to get property of non-object 

echo $data->users->id; // Error, Trying to get property of non-object 

?>

Not sure what I missed, but I can see that CActiveDataProvider was able to relate to the users table. But, when retrieve on the view using $data->users->username, simply throws an invalid get property of non-object which is weird.

Any help is appreciated!

Thanks

This is frocking insane! I was expecting an object. And yet, I can access it as an array!

WORKS!


print_r($data->users['name']);

ERROR


print_r($data->users->name);

Hi louiemiranda,

Double check your relation definitions.

When A and B are in 1:N relation, the FK of A’s HAS_MANY and the FK of B’s BELONGS_TO should be the same.

In your case, I think the definition of Recipients::users should be:




'users' => array(self::BELONGS_TO, 'Users', 'user_id'),