Honestly I didn’t know that SQLite is so forgiving until I had to migrate to MySQL in production recently.
SQLite is so forgiving that migrating to MySQL becomes a big headache. Moral of the story: always test on the DB you're going to use in prod
— Andrews Ang (@kongnir) February 27, 2015
Planning the database schema ahead of implementation was a habit, and it didn’t occur to me that the order of migrations with foreign keys was so important. SQLite didn’t produce any error, but when running Laravel migration in MySQL, it produced an error like this for tables with foreign keys:
[Illuminate\Database\QueryException] SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint (SQL : alter table `profiles` add constraint profiles_company_id_foreign foreign key (`company_id`) references `companies` (`id`))
I was so puzzled because the schema looked correct and it ran without error with SQLite. So it took me awhile to realise that only 2 tables were affected, and coincidentally that 2 tables were the first 2 to be created of all migrations.
The order of the old migrations was like this:
- 2014_01_01_00001_create_profiles_table.php
- Foreign key company_id references to id of table companies
- 2014_01_01_00002_create_contacts_table.php
- Foreign key contacttype_id references to id of table contacttypes
- 2014_01_01_00003_create_companies_table.php
- 2014_01_01_00004_create_contacttypes_table.php
That first 2 tables referenced to some tables that didn’t exist at the point of migration, that’s why MySQL had an error trying to add a constraint.
I had to change the order of the migrations for that 2 tables to be created without error.
Modified order of migrations:
- 2014_01_01_00001_create_companies_table.php
- 2014_01_01_00002_create_contacttypes_table.php
- 2014_01_01_00003_create_profiles_table.php
- Foreign key company_id references to id of table companies
- 2014_01_01_00004_create_contacts_table.php
- Foreign key contacttype_id references to id of table contacttypes
Moral of the story: Tables with foreign keys should be created after the tables they reference to have been created.
I hope this will help someone else in the future.