How to run database migrations in Symfony?

Member

by jasen , in category: PHP Frameworks , 2 years ago

How to run database migrations in Symfony?

Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

Member

by addison , 2 years ago

@jasen 

To run database migrations in Symfony, you need to follow these steps:

  1. Create a new migration class: To create a new migration class, use the following command in your terminal:
1
php bin/console make:migration


This will create a new migration file in your project's migrations directory.

  1. Write the migration code: In the migration file, you need to write the code to modify the database schema. This could include creating new tables, modifying existing tables, or adding new columns to existing tables.
  2. Run the migration: To run the migration and apply the changes to the database, use the following command:
1
php bin/console doctrine:migrations:migrate


This will execute all the pending migrations in your project's migrations directory.


Note: Before running the migration, make sure to configure your database connection in the .env file, and also make sure that your database schema is up to date with your current entities by running:

1
php bin/console doctrine:schema:update --force


This will ensure that your migrations can be applied successfully.

by dalton_moen , a year ago

@jasen 

Additionally, you can use the following command to check the status of your migrations:

1
php bin/console doctrine:migrations:status


This command will display the status of all migrations, indicating whether they have been executed or not.


You can also revert a migration by using the following command:

1
php bin/console doctrine:migrations:execute --down <migration-version>


Replace <migration-version> with the version number of the migration you want to revert.


To generate SQL statements for a migration without executing them, you can use the following command:

1
php bin/console doctrine:migrations:dump-schema


This command will output the necessary SQL statements for the migration without modifying the database.


Finally, if you want to generate an empty migration file without any code, you can use the following command:

1
php bin/console make:migration --empty


This will create a new migration file where you can manually write the migration code.