John Smith
John Smith

Reputation: 6197

Doctrine 2, update value switch

with native SQL:

UPDATE a SET active = NOT active WHERE id = 1

how to write this with Doctrine2 builder? I tried:

$q = $this->createQueryBuilder('a');
$q->update()->set('a.active', $q->expr()->not('a.active'))->getQuery()->execute();

with no luck

Upvotes: 0

Views: 75

Answers (1)

Ilya Isaev
Ilya Isaev

Reputation: 197

I think you need something like that, for Entity:

$qb = $this->em->createQueryBuilder();
$q = $qb->update('models\A', 'a')
    ->set('a.active', $qb->expr()->not('a.active'))
    ->where('a.id = ?1')
    ->setParameter(1, $id)
    ->getQuery();
$p = $q->execute();

For native SQL:

use Doctrine\ORM\Query\ResultSetMapping;
$rsm = new ResultSetMapping();

$q = $this->em->createNativeQuery('UPDATE a SET active = NOT active WHERE id = ?', $rsm);
$q->setParameter(1, $id);
$q->exectute();

For native queries without entity manager you can use:

\Doctrine\DBAL\Query\QueryBuilder

Upvotes: 1

Related Questions