I’ve decided for the first time to switch to InnoDB and experiment with foreign keys and other InnoDB features.
When creating relationships, should I declare them only on 1 table? Or both tables?
For example, for each cases below, where and how would you declare the relationships?
- 1 User has many widgets
- widget belongs to 1 user (is that same as above?)
- 1 user has 1 widget
- user [many-to-many] widgets
- many users share 1 widget
Those are just some random examples, I’m just trying to understand which directions relationships should be declared.
Also, on the same note, which direction do “ON CASCADE” stuff work?
Thanks
Assuming a widget is exclusive to one user (because you have a seperate point for many to many):
user_idon tablewidgetthat references the primary key onusersee above.
widget_idinusertable that references primary key onwidgettable, with unique index onwidget_id, or the other way around, doesn’t really matter. If it is a 1-to-1 and not a 0 or 1-to-1 relationship, you should consider putting widget and user in one table.Introduce a third table,
user_widget, with 2 fieldsuser_idandwidget_idreferencing the corresponding primary keys in user and widget table.same as “1 user has 1 widget”, but without a unique index on the
widget_idThe
ON CASCADEoption works from parent (primary key) to child (foreign key/reference). So if you have aON DELETE CASCADEin your first scenario (1 User has many widgets), delete a user deletes all his widgets, but deleting all widgets doesn’t delete the user.