Help With Relations many to many multiple tables
Posted 11 February 2013 - 10:40 AM
table 1: equipment with id_equipment. ex: Notebooks, Printers.
table 2: brand with id_brand. ex: Sony, HP.
There's a many to many relation between these two, so I have another table equipment_brand , with double PRIMARY(id_equipment, id_brand) and foreign keys for the two tables.
Now I have table 3: distributor with id_distributor. ex: 2Net, KLD.
Between the distributor and equipment_brand table, there is also a many to many relation. Which means I have another table 4: distributor_equipment_brand with triple PRIMARY(id_distributor, id_equipment, id_brand) where :
id_distributor foreign to table distributor
(id_equipment, id_brand) double foreign to equipment_brand table
Now, how do I translate this into the relations method of my Distributor model, so that using a downloaded behaviour, the relations are also saved in the triple primary key table.
I would need something like : 'varName' => array(self::MANY_MANY, 'equipment_brand', 'distributor_equipment_brand(id_distributor, array (id_equipment, id_brand))' );
Why ? Cause I have 2 foreign keys, one of which is double, and references another MANY to MANY table.
That, of course, does not work. Any help ? Or does somebody have an example of using composite foreign keys when defining a self::MANY_MANY variable.
Thank you very much.
Posted 11 February 2013 - 12:11 PM
you could replace the old primary key in equipment_brand by a new, auto-incrementing one and set a unique index to (id_equipment, id_brand).
Depending on how big your application is, this might take a lot of time for refactoring (findByPk -> findByAttributes etc...)
To give you an advice about how to handle your relations with the downloaded behavior I need to know where you downloaded it.
Posted 11 February 2013 - 12:21 PM
This is the behavior http://www.yiiframew...ation-behavior/
I think the answer is here http://www.yiiframew...elations-detail , using composite keys, however, I could not find an example anywhere and I did not managed to create one on my own.
Posted 12 February 2013 - 02:25 PM
For everyone, here's how the code looks like.
relations() defined in Distributor table:
'myVar' => array(self::MANY_MANY, 'equipment_brand', 'distributor_equipment_brand(id_distributor, id_equipment, id_brand)')
DistributorController , actionCreate for example:
Where $data is an array:
$data = array(array('id_equipment' => 1, 'id_brand' =>2), ... )
Where ... means that you can put other foreign keys, that can also be arrays.
The thing is, I had to create a model for the equipment_brand table, which I wanted to avoid, but I don't see any other way.