1

I would like to check if a record exist in the database. The only thing it needs to return is true or false. I'm now using the following query to get the record. Is the an other command as getResult() to check if the record exists?

return $this->createQueryBuilder('u')
            ->andWhere('u.email = :email AND u.id != :id')
            ->setParameter('email', $email)
            ->setParameter('id', $userId)
            ->getQuery()
            ->getResult();
1
  • 6
    The linked answer is about "How can I load the model based on email address" and the solution provided loads an instance from the database. It has nothing to do with returning a simple true/false result, the linked answer's title is misleading. Apr 5, 2019 at 18:08

1 Answer 1

9
return (boolean)$this->createQueryBuilder('u')
            ->andWhere('u.email = :email AND u.id != :id')
            ->setParameter('email', $email)
            ->setParameter('id', $userId)
            ->getQuery()
            ->getOneOrNullResult();

Please note that if it is possible (for example there is no unique index on email column) that the query returns multiple results, then you also need to wrap the call with try/catch block, because it might throw exception if more than one result are found.

2
  • 1
    You can also just add setMaxResults(1) rather than wrapping a try/catch.
    – cyzeal
    Jul 26, 2018 at 20:50
  • 12
    I suggest using $this->createQueryBuilder('u')->select('COUNT(u.id)')->getQuery()->getOneOrNullResult(\Doctrine\ORM\Query::HYDRATE_SINGLE_SCALAR) > 0; instead, to prevent hydrating the entity, associations and initializing lifecycle callbacks and event listeners.
    – Will B.
    Jan 7, 2019 at 15:29

Not the answer you're looking for? Browse other questions tagged or ask your own question.