1

我有一个带有电子邮件的注册表单,它应该是唯一的。我想做的是,如果有人填写了一封已经为另一个用户注册的电子邮件,这个人会看到一条由我写的消息,而不是类似

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

我在存储库类中试过这个:

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

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

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

然后在控制器中:

$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'));
        }

但我得到一个例外

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

我不需要查询的结果,只需要知道结果是 1 还是 0。你知道怎么做吗?

4

1 回答 1

3

你可以做:

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

顺便说一句,你看过'uniqueEntity'验证约束吗?它提供了开箱即用所需的功能:

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

于 2012-09-13T08:01:05.210 回答