MANY MANY + HAS ONE

There are 4 tables:

car 1, ford; 2, toyota

carToPerson 1,1; 2,2

person 1,2,Samdark; 2,1 Qiang Xue

nationality 1, chinese, 2 russian

I want to display following:

foreach($cars->nationality as $nat){//Nationality of a person

var_dump($nat->name.’ - '.count($nat->person));//How to know that Samdark is russian and uses ford?

}

It is easy to know how many people (and who) uses ford. But the main idea is to know correct car and person’s nationality. A person cannot be in two nationalities at the same time.

Is this idea on the right way? Is this possible at least? It seems like the db construction is wrong.

hi

you can define one relation in carToPerson that connect cars to person and called "R1".

then defiend one relation in person that connect person to nationality and called "R2"

then defiend one relation in car that connect car to carToPerson and called "R3"

then in car model, search function :

$criteria->with = array(‘R3’, ‘R3.R1’ , ‘R3.R1.R2’);

hope this helps you understand it better


// car model

	public function relations()

	{

		// NOTE: you may need to adjust the relation name and the related

		// class name for the relations automatically generated below.

		return array(

			'persons' => [static::MANY_MANY, 'Person', 'carToPerson(car_id, person_id)']

		);

	}


	// persons model

	public function relations()

	{

		// NOTE: you may need to adjust the relation name and the related

		// class name for the relations automatically generated below.

		return array(

			'persons' => [static::MANY_MANY, 'Person', 'carToPerson(car_id, person_id)']

		);

	}


	foreach($car->persons as $person) {

		echo $car->name; // will tell you the name of the car

		echo $person->nationality->name; // will tel you the nationality of the person

		echo $person->name; // name of the person

	}