user3911183
user3911183

Reputation: 797

Doctrine 2 how to increment a column for multiple rows at once?

i'm looking for a way to increment a value for multiple rows at once without looping , is it possible in doctrine ? here is the query in simple sql :

$sql = "UPDATE table set compteur = compteur + 1 where id in ('1','2','3') ";

using doctrine for updating many rows ( not incrementing ) , i have this :

$qb = $this->getEntityManager()->createQueryBuilder();
                    $query = $qb->update('Application\Entity\Table', 'l')
                            ->set('l.compteur', $qb->expr()->literal('8'))
                            ->where("l.id in ('$ids')")
                            ->getQuery();
                    $retour = $query->execute();

Thanks for any idea !!

Upvotes: 3

Views: 2960

Answers (2)

adsc
adsc

Reputation: 397

You can also do it with the querybuilder like so:

$qb->set('l.compteur', $qb->expr()->sum('l.compteur', 1));

Upvotes: 1

Ivan M
Ivan M

Reputation: 330

Use DQL for this:

$this->getEntityManager()->createQuery('
    UPDATE Application\Entity\Table t
    SET t.compteur = t.compteur + 1
')
->execute();

http://doctrine-orm.readthedocs.org/projects/doctrine-orm/en/latest/reference/batch-processing.html#dql-update

Upvotes: 1

Related Questions