Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Explicitly set Id with Doctrine when using "AUTO" strategy

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.

like image 962
Eric Avatar asked Mar 14 '11 16:03

Eric


1 Answers

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());

like image 82
nicolasbui Avatar answered Sep 28 '22 05:09

nicolasbui