我有一个带有电子邮件的注册表单,它应该是唯一的。我想做的是,如果有人填写了一封已经为另一个用户注册的电子邮件,这个人会看到一条由我写的消息,而不是类似的东西
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。你知道怎么做这个吗?
你可以做:
return count($q->getQuery()->getResult());
顺便说一句,你看过"uniqueEntity"验证约束吗?它提供开箱即用的功能:
http://symfony.com/doc/current/reference/constraints/UniqueEntity.html