Doctorine检查记录是否存在于数据库中 [英] Doctorine check if record exists in database

查看:91
本文介绍了Doctorine检查记录是否存在于数据库中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想检查数据库中是否存在记录。它唯一需要返回的是对还是错。我现在使用以下查询来获取记录。另一个命令是否作为getResult()来检查记录是否存在?

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();


推荐答案

return (boolean)$this->createQueryBuilder('u')
            ->andWhere('u.email = :email AND u.id != :id')
            ->setParameter('email', $email)
            ->setParameter('id', $userId)
            ->getQuery()
            ->getOneOrNullResult();

请注意,如果有可能(例如,电子邮件列中没有唯一索引),查询返回多个结果,然后还需要用try / catch块包装该调用,因为如果找到多个结果,它可能会引发异常。

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.

这篇关于Doctorine检查记录是否存在于数据库中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆