Alexander Bragin
Alexander Bragin

Reputation: 113

How to query UPDATE SET field = !field in Doctrine 2

I want to make a query like "UPDATE category c SET c.display = !c.display" but I get an exception.

My code:

$qb = $entityManager->createQueryBuilder();
$q = $qb->update('Category', 'c')
        ->set('c.display', '!c.display')
        ->getQuery();

$p = $q->execute();

I get an exception

Fatal error: Uncaught exception 'Doctrine\ORM\Query\QueryException' with message 'UPDATE Category c SET c.display = !c.display' in /opt/web/sites/site/vendor/doctrine/orm/lib/Doctrine/ORM/Query/QueryException.php:41
Stack trace:
#0 /opt/web/sites/site/vendor/doctrine/orm/lib/Doctrine/ORM/Query/Parser.php(448): Doctrine\ORM\Query\QueryException::dqlError('UPDATE Category...')
#1 /opt/web/sites/site/vendor/doctrine/orm/lib/Doctrine/ORM/Query/Parser.php(2586): Doctrine\ORM\Query\Parser->syntaxError('Literal')
#2 /opt/web/sites/site/vendor/doctrine/orm/lib/Doctrine/ORM/Query/Parser.php(2774): Doctrine\ORM\Query\Parser->Literal()
#3 /opt/web/sites/site/vendor/doctrine/orm/lib/Doctrine/ORM/Query/Parser.php(2708): Doctrine\ORM\Query\Parser->ArithmeticPrimary()
#4 /opt/web/sites/site/vendor/doctrine/orm/lib/Doctrine/ORM/Query/Parser.php(2676): Doctrine\ORM\Query\Parser->ArithmeticFactor()
#5 /opt/web/sites/site/vendor/doctrine/orm/lib/Doctrine/ORM/Query/Parser.php(2650): Doctrine\ORM\Quer in /opt/web/sites/site/vendor/doctrine/orm/lib/Doctrine/ORM/Query/QueryException.php on line 52

Upvotes: 1

Views: 4177

Answers (1)

FuzzyTree
FuzzyTree

Reputation: 32402

If you're using a database where a boolean is stored as 1 or 0, you could try this

$q = $qb->update('Category', 'c')
        ->set('c.display', '1 - c.display')
        ->getQuery();

See https://stackoverflow.com/a/18458617/3574819 (SO didn't let me mark as duplicate because that answer was not accepted)

Upvotes: 1

Related Questions