Doctrine 2 update from entity

Dennis picture Dennis · Apr 13, 2011 · Viewed 75.2k times · Source

Is it possible to update an entity in a similar way as below:

$data       = new ATest();  // my entity
$data->id   = 1;            // id 1 already exists, I just want to update this row
$data->name = "ORM Tested"; // changed the name

$entityManager->persist($data);
$entityManager->flush();

This will insert and change the id of the object instead of updating the existing row in the database.

Answer

Francesco Casula picture Francesco Casula · Feb 22, 2012

You should call merge instead of persist:

$data = new MyEntity();
$data->setId(123);
$data->setName('test');

$entityManager->merge($data);
$entityManager->flush();