0

I want to set the id of a new object with a specific value (that does not already exist in the database) without removing the auto-increment option of the field.

The id declaration :

#[ORM\Id]
#[ORM\GeneratedValue]
#[ORM\Column(type: Types::INTEGER, options: ['unsigned' => true])]
protected ?int $id = null;

What I want to do :

$newObject->setId(92183); // The id does not already exist in the db

Any idea how can I do that without removing the auto-increment please ?

PS : I'm using Symfony 6, I cannot find to try MetaClass method mentioned in Explicitly set Id with Doctrine when using "AUTO" strategy

Dro
  • 21
  • 3

1 Answers1

0

I checked the code of the answer you mentioned, it works fine. Here is a complete example:

# Where $this->em is EntityManagerInterface instance
$newObject->setId(92183);
$metadata = $this->em->getClassMetaData(get_class($newObject));
$metadata->setIdGeneratorType(\Doctrine\ORM\Mapping\ClassMetadata::GENERATOR_TYPE_NONE);
$metadata->setIdGenerator(new \Doctrine\ORM\Id\AssignedGenerator());
$this->em->persist($newObject);
$this->em->flush();

However you should be careful with it, because this behavior (I guess) will be affect all created entities of this type until the end of the request.

Therefore, it might be better to save the previous metadata settings, and return them after saving a specific entity.

$prevGeneratorType = $metadata->generatorType;
$prevIdGenerator = $metadata->idGenerator;
# ... the code mentioned above ...
$metadata->setIdGeneratorType($prevGeneratorType);
$metadata->setIdGenerator($prevIdGenerator);
vodevel
  • 144
  • 4