Doctrine 2: Update query with query builder
To update an entry in a database using Doctrine's query builder, you can use the update method of the QueryBuilder class.
To update an entry in a database using Doctrine's query builder, you can use the update method of the QueryBuilder class. Here's an example of how you can do it:
Example of updating query with query builder in Doctrine 2
<?php
$queryBuilder = $entityManager->createQueryBuilder();
$queryBuilder
->update('MyEntity', 'e')
->set('e.field1', $newValue1)
->set('e.field2', $newValue2)
->where('e.id = :id')
->setParameter('id', $id);
$query = $queryBuilder->getQuery();
$query->execute();This will create and execute an UPDATE query that sets the field1 and field2 fields of the MyEntity entity to the specified new values, for the entity with the specified id. Note that update() is a DML operation and does not return the updated entity instance.
You can also use the set method to set multiple fields at once, like this:
Example of using the set() method to set multiple fields at once in Doctrine 2
<?php
$queryBuilder
->update('MyEntity', 'e')
->set('e.field1', $newValue1)
->set('e.field2', $newValue2)
->where('e.id = :id')
->setParameter('id', $id)
->getQuery()
->execute();Here, $newValue1 and $newValue2 are the new values for the respective fields. Doctrine's set() method must be called for each field you wish to update; it does not accept an associative array for bulk updates.