DEV Community

Cover image for Symfony/Doctrine migrations for multiple databases
Rafael Beraldo
Rafael Beraldo

Posted on

Symfony/Doctrine migrations for multiple databases

In Symfony/Doctrine, when running the command php bin/console make:migration it generates the migrations for the current driver only, unfortunately it doesn't generate database-agnostic code.

But it can be easily customized. Let's setup it to generate two migrations, one for MySQL (prod/dev) and one for SQLite (test).

Setup

Setup your MySQL in your .env like you would usually do, but set a MIGRATIONS_PATH="migrations/mysql" property to it.

Then create a .env.test and set:

APP_ENV=test
DATABASE_URL="sqlite:///%kernel.project_dir%/var/data.db"
MIGRATIONS_PATH="migrations/sqlite"
Enter fullscreen mode Exit fullscreen mode

In your config/packages/doctrine_migrations.yaml you change default path to get from the env files:

doctrine_migrations:
    migrations_paths:
        'DoctrineMigrations': '%kernel.project_dir%/%env(string:MIGRATIONS_PATH)%'
    enable_profiler: false
Enter fullscreen mode Exit fullscreen mode

Also enable MakerBundle for test env in config/bundles.php:

Symfony\Bundle\MakerBundle\MakerBundle::class => ['dev' => true, 'test' => true],
Enter fullscreen mode Exit fullscreen mode

Running migrations

Now you can work with migrations using:

# for MySQL
php bin/console make:migration
php bin/console doctrine:migration:migrate

# for SQLite
php bin/console make:migration --env=test
php bin/console doctrine:migration:migrate --env=test
Enter fullscreen mode Exit fullscreen mode

Doing this, Symfony will generate migrations for MySQL in migrations/mysql and migrations/sqlite for SQLite.

Top comments (0)