problem with relations

Some reason I can’t get my relations to work anymore.

I create a new Log model instance, set the $log->user_id to something, and then try to access the user with $this->user, and it doesn’t work. Here’s my code:


	public function relations() {

		return array(

			'user' => array(self::BELONGS_TO, 'User', 'user_id', 'alias'=>'user'),



	protected function beforeSave() {

	//at this point, $this->user_id is set to something appropriate, i verified this.

		$this->challenge_id = $this->user->client->challenge_id; //throws error: $this->user is a non-object

		return parent::beforeSave();


I believe this is caused by relation alias being the same as relation name.

hmm… testing

No, that’s not the problem… I think it has to do that the record is a new one (isNewRecord returns true). But it should work, still…

This is a Yii problem.

We had a long discussion about it with qiang in the forum.

I think Yii should be changed in this point but Qiang does not agree

Have a look here for his reasoning:

Relations access problem.

Ah, thanks! i’m going to write a constructive argument over there…

We’ll, I was about to argue it, but then I realized there was a better solution that saved on the DB.

If you know the id of the related record, haven’t you already loaded the related record (just under a different variable)? You may have.

I think it is not a good practice, it’s a overuse of relations feature.

I agree to Qiang.