Search code examples
cakephpcakephp-3.0database-migration

Cakephp 3.x migration: define foreign key dependencies / execution order


System

  • CakePHP Version: 3.4.6
  • Platform and Target: MySQL 5.7, Windows 10

Problem

I'm defining a column as a foreign key within a migration B which needs a prior table A to exist / migration executed.

What happens

Of course the error SQLSTATE[HY000]: General error: 1215 Cannot add foreign key pops up because the migration of table A must be executed first so that B can define it's foreign key.

Question

Can I define the execution order / dependencies within the migrations or do I have to execute the migrations one by one by hand?


Solution

  • The order is determined by the version (datetime) prefix of the migration filenames, they are being executed in ascending order, ie from the earliest to the latest version. Rollbacks are executed in descending order, ie from the latest to the earliest (as of Phinx 0.8, the rollback order can be defined via the version_order option).

    So if you need your migrations to be applied in a specific order, set the versions of the filenames accordingly. Alternatively apply the changes in a single migration file.