Doctrine 2: Update query with query builder

CarlM picture CarlM · Dec 2, 2010 · Viewed 134.4k times · Source

Hi I've got the following query but it doesn't seem to work.

$q = $this->em->createQueryBuilder()
    ->update('models\User', 'u')
    ->set('u.username', $username)
    ->set('u.email', $email)
    ->where('u.id = ?1')
    ->setParameter(1, $editId)
    ->getQuery();
$p = $q->execute();

This returns the following error message:

Fatal error: Uncaught exception 'Doctrine\ORM\Query\QueryException' with message '[Semantical Error] line 0, col 38 near 'testusername WHERE': Error: 'testusername' is not defined.' in ...

I would be glad of any help

Answer

rojoca picture rojoca · Dec 2, 2010

I think you need to use Expr with ->set() (However THIS IS NOT SAFE and you shouldn't do it):

$qb = $this->em->createQueryBuilder();
$q = $qb->update('models\User', 'u')
        ->set('u.username', $qb->expr()->literal($username))
        ->set('u.email', $qb->expr()->literal($email))
        ->where('u.id = ?1')
        ->setParameter(1, $editId)
        ->getQuery();
$p = $q->execute();

It's much safer to make all your values parameters instead:

$qb = $this->em->createQueryBuilder();
$q = $qb->update('models\User', 'u')
        ->set('u.username', '?1')
        ->set('u.email', '?2')
        ->where('u.id = ?3')
        ->setParameter(1, $username)
        ->setParameter(2, $email)
        ->setParameter(3, $editId)
        ->getQuery();
$p = $q->execute();