relating three tables

hi…

i want to know if it is possible to connect three tables using relations… Here’s an example…

I have 3 tables

1)members fields are (Member_ID(primary key),Nickname,Label)

2)alerts fields are (Alert_ID(primary key),Post_ID)

3)posts fields are(post_ID(primary key),Member_ID,Post_Name)

Now,

-alert table is related on posts using this relation

‘post’ => array(self::BELONGS_TO, ‘Posts’, ‘Post_ID’),

-post table is related on members using this relation

‘member’ => array(self::BELONGS_TO, ‘Members’, ‘Member_ID’)

now if i want to know the "Label" value of the member who posted a post when i am in alerts model, is it possibble to right the relation this way?

$alerts=Alerts::model()->find();

$label=$alerts->post->member->Label

if no, what is the alternative way?

When you access the relation of the model, like $model->relationName, you gather access to the relationName model relations too, so things like $model->relationName->SomeRelationInRelationName->name is perfectly valid, as long as the relation "relationName and SomeRelationInRelationName" returns only a single instance of the related model.

In case these returns multiple instances(arrays), then you’ll have to loop through them.

Hi,

I just tried your solution, and it works perfectly.

My version of the 3 tables is: Region / Province / City each related to the previous one, so province with region, and city with province.

I wanted to show region / province / city for any given city i search.

The solution was to create the relations like so:

region:


'provincii'=>array(self::HAS_MANY, 'Provincie', 'id_regiune'),



province:


'regiune'=>array(self::BELONGS_TO, 'Regiuni', 'id_regiune'),

city:


'provincie'=>array(self::BELONGS_TO, 'Provincii', 'id_provincie'),

and on the view i put:


if (isset($_POST["oras"])){

	$orase = Orase::model()->findAll(array("condition"=>"nume_oras like '%".$_POST["oras"]."%'","order"=>"id_oras"));

	//$orase = Orase::model()->findByPk(5);

	

	foreach ($orase as $orase_gasite):

		echo "Regiunea:".$orase_gasite->provincie->regiune->nume_regiune." Provincia:".$orase_gasite->provincie->nume_provincie." Oras:".$orase_gasite->nume_oras."<br>";

	endforeach;

}

But what i am not sure, is if i did the search correctly, and if there is another way to perform this search.

One field where the user inserts the city he is looking for, and then the search form returns the results.

I have created on the view page a form with the action in index (the form is on the front page), but i am sure there is a better way than hardcoding the form in that file.