Many To Many With Attributes

Hello

I would like to add attributes to a Many-To-Many relation with Yii,

For example, lets assume i have Person and Car entities, with a many-to-many relation : a person can drive many cars and a car can be driven by many persons. But lets imagine that the person can define preferences for the cars he can drive (for a person, cars are now ordered thanks to an integer parameter) or even a price that changes according to persons and cars.

In the database model, there should be a table like that (id_car, id_person, order, price). How can i do that with yii ? I cant find it in the documentation.

Thank for the help

Hi zagor,

In that case we’ll have two 1:n relations instead of one MANY_MANY relation.

A Person HAS_MANY PersonCars, and a PersonCar BELONGS_TO a Car.

And a Car HAS_MANY PersonCars, and a PersonCar BELONGS_TO a Person, from the other way around.

Thanks Softarks, but do you have some example?

We can establish ‘personCars’ HAS_MANY relation in Person model and ‘car’ BELONGS_TO relation in PersonCar model, instead of ‘cars’ MANY_MANY relation in Person model. Then we can use those relations as the following:




$persons = Person::model()->with('personCars', 'personCars.car')

    ->findAll(array('order' => 't.name, personCars.order'));

foreach($persons as $person) {

    echo "PERSON : name = " . $person->name . "\n";

    foreach($person->personCars as $personCar) {

        echo "CAR : " . $personCar->car->name . "\n";

        echo "MODEL : " . $personCar->car->model . "\n";

        echo "PRICE : " . $personCar->price . "\n";

    }

}



In fact, any MANY_MANY relation can be divided into a set of HAS_MANY + BELONGS_TO relations.

Hey

I would suggest a Many to Many as in Has and Belongs to Many relationship, but as @softark pointed out, you can can devide them into a set of HAS_MANY + BELONGS_TO relations in order to understand what is going on better.

Regards