Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Most efficient way to tell if an entity exists in Doctrine 2

I'm creating a registration form and want to check to see if an email is not already associated with an account. All the ways I can see will create the entire User entity, but I just need to know if it exists.

like image 478
Logan Bailey Avatar asked Feb 18 '12 12:02

Logan Bailey


2 Answers

  public function isUnusedEmail($email) {
    $em = static::$pimple['em'];
    $dql = 'SELECT 1 FROM App\Model\User user WHERE user.email = :email';
    $query = $em->createQuery($dql);
    $query->setParameter('email', $email);

    $res = $query->getResult();
    return empty($res);
  }
like image 185
Logan Bailey Avatar answered Oct 10 '22 14:10

Logan Bailey


Consider the following method:

/**
 * @param string $token
 * @return bool
 */
public function isTokenUnique($token)
{
    $manager = $this->getEntityManager();

    /** @var Doctrine\ORM\Query $query */
    $query = $manager->
        createQuery('SELECT 1 FROM AppBundle:Member m WHERE m.token = :token')
            ->setParameter('token', $token)
            ->setMaxResults(1)
    ;

    return (count($query->getResult()) == 0);
}

Notice a call to setMaxResults(). It can be important in some cases.

like image 26
Slava Fomin II Avatar answered Oct 10 '22 14:10

Slava Fomin II