简体   繁体   中英

How to count the number of rows in a query when in most cases, they are expected to be 0 - Doctrine2

I have a register form with email which should be unique. What I want to do is, if someone fills in an email which is alreday registered for another user, this someone to see a message, written by me, not something like

SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry 'admin@domain.com' for key 'UNIQ_1483A5E9E7927C74'

I tried this in the repository class:

public function getSameFriends ($email)
    {
        $q = $this->createQueryBuilder('f');

        $q->select('f')
          ->where('f.email = :email')      
          ->setParameter('email', $email);

        return $q->getQuery()->getSingleScalarResult();
    }

and then this in the controller:

$em = $this->getDoctrine()->getEntityManager();
        $count = $em->getRepository('EMMyFriendsBundle:Friend')
                                    ->getSameFriends($friend->getEmail());
        if($count != 0)
        {
            $this->get('session')->setFlash('notice', 'There already is a friend with this email!');
            return $this->redirect($this->generateUrl('home_display'));
        }

but I get an exception that

No result was found for query although at least one row was expected.
500 Internal Server Error - NoResultException

I don't need the result of the query, just to know if the results are 1 or 0. Do you have any idea how to make this?

You can do:

return count($q->getQuery()->getResult());

BTW, have you looked at the 'uniqueEntity' validation constraint? It provides the functionality you need out of the box:

http://symfony.com/doc/current/reference/constraints/UniqueEntity.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM