You might not want to use entity manager / repository in a Doctrine migration

You might not want to use entity manager / repository in a Doctrine migration

But why? It's so appealing. The simple answer: You're going to loose the opportunity to run the migrations from the beginning.

Let me explain:
Usually you're able to put your initial database schema in the initial migration and with every change, create a new migration. This way you can migrate up and down over your whole repository. Within the migration you use addSql methods to add sql queries which are executes after all are read in (kind of obivous). Native queries are used for a reason here.

Whenever the entity manager (for example as part of a repository) is used, the entities are managed according to the current state of the entity configuration. For example your entity PHP class with annotations. Which means that as soon as you add another column or rename an existing one, your current table schema and the entity configuration won't be the same. Which will lead to an error when executing the migration.

The mean part of such an error is, that everything will look fine when you're writing and executing the migration on the server. But a few commits or deployments later you might change the underlaying entity configuration and then it will fail. But only when you're executing this migration again.

This means two things:

  1. You might go for years without realizing that you lost the possibility to migrate from the beginning.
  2. You might not need to care. If you only use the migrations to go one step at a time, you are able to use entity managers. I just wouldn't recommend it as a default.

The first time I ran into it, was when the repository was already a year old. We then rewrote the existing migrations with entity manager usage to native queries. That is still an option.