When working with models/tables that have a many-to-many relationship, what is the correct way to define the relationships in each model’s relations() method?
The app I am currently working on is my first real-world Yii app, and when I generated the models (via the "model *" command), the shell generated models for both of the associative tables I am using.
So, I assumed I needed to define relationships for them, too, in order for the MANY_MANY relationships to function properly.
This is how I defined the relationships initially:
# Table A:
public function relations()
{
return array(
'thingB'=>array(self::MANY_MANY, 'classThingB', 'TableA_TableB(tableA_id, tableB_id)'),
'thingAThingB'=>array(self::HAS_MANY, 'classThingAThingB', 'tableA_id'), # Associative table
);
}
# Table B:
public function relations()
{
return array(
'thingA'=>array(self::MANY_MANY, 'classThingA', 'TableA_TableB(tableA_id, tableB_id)'),
'ThingAThingB'=>array(self::HAS_MANY, 'classThingAThingB', 'tableB_id'), # Associative table
);
}
# And the associative TableA_TableB:
public function relations()
{
return array(
'thingA'=>array(self::BELONGS_TO, 'classThingA', 'tableA_id'),
'thingB'=>array(self::BELONGS_TO, 'classThingB', 'tableB_id'),
);
}
After watching the blog tutorial screencast, however, I’m now thinking that it is unnecessary to define relationships for associative tables. But I am not sure. And, I am wondering, is it even necessary to have model classes to represent the associative tables? (I think it is; otherwise, how would Yii know how to relate them?)
Could anyone please help to clear up my confusion by detailing exactly how MANY_MANY relationships should be defined in Yii?
Thanks in advance,
Tom