Search code examples
moduleyii2database-migrationyii2-module

Yii2: How to modify tables created by module migrations?


Say we add a 3rd party module that comes with a bunch of migrations, and one of the migrations creates a post table. What if we want to modify this table? We may want to add another column, or add a foreign key and link it to one of our project's existing tables. How do we ensure all the migrations always occur in the correct order if the order is fixed based on the migration name (by timestamp) that comes with the module?


Solution

  • Alright so here is my solution. Let's take a generic "forum" module as an example.

    To apply the "forum" module migrations we can do one of the two things:

    1. Run ./yii migrate --migrationPath=@app/modules/forum/migrations. This will simply apply the migrations in that folder. It will not copy, nor rename them. This mean that even running migrate/redo will fail, because yii will expect that migration to be in the main project's migration path.

    2. To resolve the above issue, Yii2 developers implemented migration namespaces. What we can do is add the module's migration namespace to our application config and then run ./yii migrate. This is better, but still flawed. We still cannot modify the module's migrations, because we cannot control their names which determine the execution order!


    Neither of the above works if we want to modify migrations. Here is what you can do:

    Create a new empty migration in your project, but don't extend from yii\db\Migration. Instead, extend it from the migration defined in the module. Do this for every migration file contained in the module. This way you can have full control of the execution order (you can give them any name you like) and you can even modify those migrations by overriding their up()/down() methods.

    Better ideas / improvements are welcome!