Yesterday I had an annoying issue while adding a Sluggable behaviour to an existing entity in my Symfony 2.1 project.
The issue was simple: since the slug field should be defined as NOT NULL and my DB was full of existing records, the migrations failed with a mysql #1062 - Duplicate entry due to the fact that all the existing records have, of course, the same empty value for the slug after its creation.
What I had to do was setting the slug field as NULLABLE, update the slugs, then set it to NOT NULL again.
So I thought of replicating the behavior of the Sluggable on the DBAL layer with custom queries, but this felt like reinventing the Sluggable's wheel, with too much checks to do (slug uniqueness, slugged fields, composition, etc).
So I decided to let a symfony command do the job for me.
I defined a service for recalculating the slugs:
and making it a service in service.yml:
Then I defined the command:
Then I defined the first new migration, setting the slug field as NULLABLE and calling the update-slugs command in the postUp event:
Finally I added another migration where I set the slug field back to NOT NULL:
As you can see I did a little hacking here: I booted the kernel and used a command tester in order to launch the command. Not the most elegant way, but this worked and will work for any entity I need to slug in the future.