问题
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:
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.
来源:https://stackoverflow.com/questions/36801089/doctorine-check-if-record-exists-in-database