Symfony Doctrine Foreign Key Error

Travis Black's picture

SQLSTATE[HY000]: General error: 1005 Can't create table X (errno: 150). Failing Query: ALTER TABLE tablename ADD FOREIGN KEY (key_id) REFERENCES table(id)

Ever seen an error message like that before? Many of us have and its a big ole pain in the butt, but never fear, because the fix is simple.

There is an issue with your ID columns. Normally this has to do with the foreign key and primary keys having different length constraints. Your fix:

Make sure that the length constraints match. If you aren't specifying a length, you can simply remove the ID field from your schema.yml, and let Doctrine create it for you, or if you want to be explicit, you can set a length and make sure it is matched in the related foreign key field.

Note: If you are working with sfDoctrineGuard, you must make sure that you define the related field as integer(4)

Examples:

Custom Classes:

Without defining length:

School:
columns:
name: string(255)


Student:
columns:
name: string(255)
grade: string(255)
age: integer(4)
school_id: integer
relations:
School:
local: school_id
foreign: id
foreignAlias: Students

With Defined Length:

School:
columns:
id: integer(4)
name: string(255)


Student:
columns:
name: string(255)
grade: string(255)
age: integer(4)
school_id: integer(4)
relations:
School:
local: school_id
foreign: id
foreignAlias: Students

sfGuard Related Model:

sfGuardUserProfile:
columns:
user_id: integer(4)
email: string(255)
age: integer(4)