Doctrine 2: Update query with query builder

2019-01-17 02:22发布

问题:

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

回答1:

I think you need to use Expr with ->set():

$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();

Either that or make all your values parameters:

$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();


回答2:

Let's say you have some backend showing a list of users (accessible by few admins who might have read/write access on users details).
There you may print users id on their own row as a data attribute in order to retrieve it from Javascript while some event get triggered.

Then an update can be executed this way …

class UserRepository extends \Doctrine\ORM\EntityRepository
{
    public function updateUserStatus($userId, $newStatus)
    {
        return $this->createQueryBuilder('u')
            ->update()
            ->set('u.isActive', '?1')
                ->setParameter(1, $qb->expr()->literal($newStatus))
            ->where('u.id = ?2')
                ->setParameter(2, $qb->expr()->literal($userId))
            ->getQuery()->getSingleScalarResult();
    }

And inside the (ajax) handling action …

    # Post datas may be handled with a specific custom formType
    # … OR …
    # Directly retrieved from request object
    $userId = (int)$request->request->get('userId');
    $newStatus = (int)$request->request->get('newStatus');
    $em = $this->getDoctrine()->getManager();
    $r = $em->getRepository('NAMESPACE\User')
            ->updateUserStatus($userId, $newStatus);
    if ( !empty($r) ){
        # Row updated
    }
    # …

Working example using Doctrine 2.5 (on top of Symfony3).