Doctrine 2 update from entity

Doctrine 2 update from entity

  1. Blog
  2. 15 November 2026
  3. 4 min read

Stefan Bogdanescu

Founder & Senior Architect

Why persist() Fails for Updates and How to Fix It

Attempting to update an existing row by calling $entityManager->persist($data) after manually setting the primary key is a common point of confusion when working with Doctrine ORM. The code snippet you provided will indeed insert a new row into the database, not update an existing one. This happens because persist() tells the EntityManager that the object is new and should be inserted. When Doctrine flushes the changes, it executes an INSERT statement using the ID you manually assigned ($data->id = 1). Since a row with id = 1 already exists, most databases will throw an integrity constraint violation (like a unique key error), or if the ID is auto-incremented and not explicitly part of the primary key logic in your schema, it might behave differently depending on configuration.

To correctly update an existing entity, you must signal to the EntityManager that the object already exists in the database. The standard approach is to load the existing entity first using its identifier and then modify its properties.

// Load the existing entity by ID
$existingEntity = $entityManager->getRepository(ATest::class)->find(1);

if ($existingEntity) {
    // Now you can safely modify the properties
    $existingEntity->setName('ORM Tested');
    
    // Flush will generate an UPDATE statement because Doctrine 
    // knows this entity is already managed and persisted.
    $entityManager->flush();
}

When you call find() or getOneOrNull(), Doctrine attaches the existing database state to that object instance in memory. This creates a "managed" state. Once an object is managed, any changes made to its properties are tracked by the Unit of Work pattern used internally by Doctrine. When you subsequently call flush(), Doctrine inspects the dirty tracking mechanism to determine whether to issue an INSERT or an UPDATE. Because the object was loaded from the database, Doctrine knows it corresponds to an existing row and generates the appropriate UPDATE SQL statement.

If you prefer not to load the entity first, you can use merge(). The merge() method is designed specifically for this scenario where you might have a new instance that represents an existing row but hasn't been attached to the current EntityManager yet.

$data = new ATest();
$data->id = 1;
$data->name = "ORM Tested";

// merge() attaches the state of $data to the existing entity in the EntityManager
// and marks it as updated for the next flush, without creating a new row.
$entityManager->merge($data);
$entityManager->flush();

However, merge() is often an unnecessary abstraction if you simply want to update a specific record. Loading the entity via the repository is usually more explicit and easier to debug. It allows you to check if the entity exists before attempting to modify it, preventing potential errors on non-existent IDs.

When to Use persist() vs. merge()

The distinction lies in the lifecycle of the object:

  • persist(): Use this when you have a brand new object that does not exist in the database yet. It prepares the object for insertion.
  • merge(): Use this when you want to update an existing record but currently hold an unmanaged instance (often created from a DTO or JSON response) that maps to an existing ID.
  • Direct modification of a managed entity: If you already have the entity in your session (loaded via find), simply modify its properties and flush. No special method is needed.

Potential Pitfalls

One subtle issue arises when dealing with auto-incremented primary keys. In your example, $data->id = 1 assumes that ID 1 is the target for update. If your database uses an auto-increment strategy (like AUTO_INCREMENT in MySQL or IDENTITY in SQL Server) and you manually set the ID on a new object before persisting, Doctrine might still attempt to generate its own value depending on the driver and configuration settings. However, if the column is strictly a primary key with a unique constraint, setting it manually works for updates provided the entity is marked as managed (via find or merge).

Another consideration is transaction management. If you load an entity, modify it, and then flush within a long-running request without explicitly handling transactions, you might run into race conditions if multiple processes are updating the same row simultaneously. While Doctrine handles concurrency via optimistic locking (using version fields) out of the box for mapped entities, being aware of this is crucial for high-concurrency applications.

For developers looking to streamline their data access patterns further, frameworks like LaravelCompany often integrate tightly with these ORM concepts, providing elegant facades that abstract away some of the boilerplate required to manage entity lifecycles efficiently.

Our network