1

My straight forward question:

If I have a many-to-many relation in my database (as the following tables)

User          Role          UserRole
  user_id       role_id       user_id
                              role_id

Should UserRole have its own Model when connecting this database to a MVC framework?

In context:

I'm rewriting my completely self-written web service with a MVC framework and I decided to use Yii. I have the option to generate a lot of code from my database tables but I got confused whether to Model the many-to-many relation tables (like UserRole above).

Thanks in advance!

tereško
  • 58,060
  • 25
  • 98
  • 150
jelgh
  • 705
  • 1
  • 6
  • 22
  • I'm not sure if this example (Users and Roles) is a MANY-MANY relationship. Cos it's more like each User having one Role and each Role having many Users. But, anyways, for a many-many relationship, your relation definition would be like: `return array( 'roles'=>array(self::MANY_MANY, 'Role', 'user_role(user_id, role_id)'), ); ` with `user_role` being the join table and `user_id` and `role_id` being the foreign keys. – Oladapo Omonayajo Jul 25 '13 at 09:03
  • So you mean that UserRole should not have it's own Model, right? I'm really new to Yii sry – jelgh Jul 25 '13 at 09:06
  • 1
    Yes. `UserRole` wouldn't need it's own model – Oladapo Omonayajo Jul 25 '13 at 09:12
  • @ragingprodigy For some applications, users can have multiple roles. – Sam Jul 25 '13 at 09:33
  • @Sam well, that's also true. That's why I answered the question anyway :D – Oladapo Omonayajo Jul 25 '13 at 09:56

2 Answers2

2

I mostly use the code-first approach and there defining the relation table is optional for many-to-many relationships. Going from this, I'm assuming that the MVC framework in general considers this to be optional. So, the answer would be:

Must UserRole have its own Model? No.

Can UserRole have its own Model? Yes.

Should UserRole have its own Model? If your many-to-many only contains two id's, I would not add it to the model.

Sam
  • 1,358
  • 15
  • 24
0

for a many-many relationship, your relation definition would be like: return array( 'roles'=>array(self::MANY_MANY, 'Role', 'user_role(user_id, role_id)'), ); with user_role being the join table and user_id and role_id being the foreign keys.