Data migration with Doctrine2

The cause

As it turns out, the cause of the problem is the fact that when you specify strategy=”AUTO” for your ID-field, Doctrine2 will ignore any existing ID you’ve set in the entity. It will generate one because, well, you’ve specified it should be doing this. And usually, this is correct behaviour, but with the migration of existing data, to retain correct relations etc, it is much easier to keep the old IDs.

The solution

The solution is easy and, as usual, I found it thanks to StackOverflow. In your migrationscript, for each of the entities you’re migrating, you just temporarily turn off the strategy: As soon as I had added the above snippet for all the entities I’m migrating, it kept the old IDs and migration all of a sudden went flawlessly.

Update: The above method assumes you have a way of setting the ID in the entity, for instance a setId() method.