Defining MANY_MANY Relationships

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

You only need to define relations in those models, where you want to access the related objects of that model. So if you never do $thingB->thingA, you don’t need to define that relation in thingB. Even though it doesn’t hurt either :).

For the connecting table in a MANY_MANY relationship: No, it doesn’t need a model class, if you only want to access the related objects. But a model class is handy as soon as you want to edit (add/delete) these relations.