My entity uses this annotation for it's ID:
/** * @orm:Id * @orm:Column(type="integer") * @orm:GeneratedValue(strategy="AUTO") */ protected $id;
From a clean database, I'm importing in existing records from an older database and trying to keep the same IDs. Then, when adding new records, I want MySQL to auto-increment the ID column as usual.
Unfortunately, it appears Doctrine2 completely ignores the specified ID.
New Solution
Per recommendations below, the following is the preferred solution:
$this->em->persist($entity); $metadata = $this->em->getClassMetaData(get_class($entity)); $metadata->setIdGeneratorType(\Doctrine\ORM\Mapping\ClassMetadata::GENERATOR_TYPE_NONE); $metadata->setIdGenerator(new \Doctrine\ORM\Id\AssignedGenerator());
Old Solution
Because Doctrine pivots off of the ClassMetaData for determining the generator strategy, it has to be modified after managing the entity in the EntityManager:
$this->em->persist($entity); $metadata = $this->em->getClassMetaData(get_class($entity)); $metadata->setIdGeneratorType(\Doctrine\ORM\Mapping\ClassMetadata::GENERATOR_TYPE_NONE); $this->em->flush();
I just tested this on MySQL and it worked as expected, meaning Entities with a custom ID were stored with that ID, while those without an ID specified used the lastGeneratedId() + 1
.
Although your solution work fine with MySQL, I failed to make it work with PostgreSQL as It's sequence based.
I've to add this line to make it work perfectly :
$metadata->setIdGenerator(new \Doctrine\ORM\Id\AssignedGenerator());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With