Delete Your Code #5: Use foreign keys

db, delete your code Add comments

A foreign key, this classic concept of relational databases, is extremely helpful in many ways.

To start with, it’s a watch dog of your database integrity — for example, it would be impossible to add user images records, if the user does not exist. No additional code, more control.

Another benefit is that all depending data is deleted cascadedly when the parent row gets killed. You remove a user — and voila: all images, comments, ratings and staff fly away too.

And third, it helps to autogenerate admin tools; for instance, in Symfony framework, the generator of admin interface relies on this info.

To be able to use foreign keys in your MySQL database, do 2 following steps:

  • make sure the two tables you are connecting, are driven by InnoDB
  • ensure that the columns you connect (user_id in our example) are of exactly the same type, including NULL and sign allowance.

Comments are closed.

WP Theme & Icons by N.Design Studio
Entries RSS Comments RSS Log in