Yii UActiveRecord Relations

Hi all,

I am new to Yii, and I am trying to get an App build using this great Framework, However, I have a question that I haven’t been able to answer reading the docs…

I have 3 tables related as follows:

Profiles --> Profiles_Pictures --> Pictures

Its a many to many relation between Profiles and pictures, meaning That 1 user can have many pictures for his profile.

So I created a model Profile, and a model called Picture.

In the Profile model, I set the following relation:


public function relations()

	{		

		$relations = array(			

			'pictures'=>array(self::MANY_MANY, 'ProfilePictures', 'profiles_profilespictures(ProfileID,ProfilePictureID)'),

		);		

		return $relations;

	}



This works pretty good, every time I do $model->pictures it returns the related pictures…

But, and here comes my question, I would like to obtain only the picture set as Default (its one boolean field in Picture’s table)

I tried with scopes, with no luck. can anyone tell me if there is a way to filter just the picture marked as default using the Profile model Relation?

If one user has many pictures, isn’t it supposed to be HAS_MANY relationship instead of MANY_MANY? Oh well, I am not a relation expert, so feel free to correct me if I misunderstood your situation. :)

If I understand your problem correctly, I think this is the same with my problem with the ‘current status’, wherein the user has many status saved in the db table but only one should be rendered in the page, whichever status is marked as ‘active’. My workaround for this was to create a separate function to query the active status of the user, which I think is not the Yii-way to solve it.

Apologies if I should create a new issue for this. I just thought that Julio and I have a problem with the same logic, and I hope that answer for his situation will also serve as an answer for me.

I have found the solution to this, reading more in depth the Yii documentation.

for my specific case, I just had to do this to get just one picture:




$picture = Profile::model()->with('pictures:mypicture')->findByPk($user->id);



where pictures is the relation name on the class Profile and mypicture is the scope defined on the related class Picture.

this is the scope I have defined in the related table Pictures




public function scopes(){

		return array(

			'mypicture'=>array (

			     'condition'=>'Default=1',	 

		),

		);

	}



And this is my relation defined in Profile model:




public function relations()

	{		

		$relations = array(			

			'pictures'=>array(self::MANY_MANY, 'ProfilePictures', 'profiles_profilespictures(ProfileID,ProfilePictureID)'),

		);		

		return $relations;

	}



I hope this will help someone else with the same problem.

Thanks for posting your solution,Julio