Trouble with MySQL Foreign Keys?

There I was, coding up a fresh Doctrine schema for a Symfony app, when my plans to implement foreign keys were repeatedly foiled:

SQLSTATE[HY000]: General error: 1005 Can’t create table ‘./mydb/#sql-xxxx.frm’ (errno: 150). Failing Query: ALTER TABLE cow ADD FOREIGN KEY (barn_id) REFERENCES barn(id)

I was using InnoDB, both tables were there, both columns were there, what else could MySQL want? Why didn’t it work?

Apparently, you must use the same data type for both columns. My cows.barn_id was an INT, while barns.id was a SMALLINT. This didn’t fly. Changing both to SMALLINT did the trick.

Hint: if you’re using Symfony with Doctrine, like I am, use “integer(4)” to get the MySQL INT datatype, or “integer(2)” for a SMALLINT data type. Plain old “integer” converts to BIGINT.

This entry was posted in Angry Development Tips, Technology. Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>