Symfony2 Doctrine force entity ID on persist

Let’s say you need to create some records in your database with specific IDs (for example you want to import something from an older database).

The first thing you will notice is that the generated entity has no setId() method, so you will need to add one:

public function setId($id)
{
    $this->id = $id;
}

Then, if you try to save a new object with the custom ID you want, you will notice that it is ignored and the ID is generated as always. To change this use the following example:

$entity = new Product();
$entity->setId(1);
// ...
$em->persist($entity);

$metadata = $em->getClassMetaData(get_class($entity));
$metadata->setIdGeneratorType(\Doctrine\ORM\Mapping\ClassMetadata::GENERATOR_TYPE_NONE);

$em->flush();

Now the new record will have the exact ID you want.

3 thoughts on “Symfony2 Doctrine force entity ID on persist”

  1. Hi,

    There is a little missing piece to make it work flowlessly (I’ve search a while to make it work with PostgreSQL).
    You should always add this :
    $metadata->setIdGenerator(new \Doctrine\ORM\Id\AssignedGenerator());

    Best regards,

  2. Thank you Dragos and Nicolas for your tips.

    I figured out, that you should put it before $em->persist(...). Otherwise persist might create an ID for you (e.g., if you use the UUID() generator or a custom one).

    So the updated version should look something like this:

    $entity = new Product();
    $entity->setId(1);
    // ...
    $em->getClassMetaData(get_class($entity))->setIdGenerator(new \Doctrine\ORM\Id\AssignedGenerator());
    $em->persist($entity);

    $em->flush();

    Cheers

Leave a Reply

Your email address will not be published. Required fields are marked *