使用 Doctrine NativeQuery 获取单行结果

2022-08-30 09:32:37

我正在尝试从带有 Doctrine 的本机查询返回一行。这是我的代码:

$rsm = new ResultSetMapping;
$rsm->addEntityResult('VNNCoreBundle:Player', 'p');
$rsm->addFieldResult('p', 'player_id', 'id');

$sql = " 
    SELECT player_id
      FROM players p
     WHERE CONCAT(p.first_name, ' ', p.last_name) = ?
";

$query = $this->getEntityManager()->createNativeQuery($sql, $rsm);
$query->setParameter(1, $name);
$players = $query->getResult();

最后一行返回玩家列表,但我只想要一个结果。我该怎么做?


答案 1

可以使用 ,如果找到多个结果或未找到任何结果,则会引发异常。(请参阅此处的相关 phpdoc https://github.com/doctrine/doctrine2/blob/master/lib/Doctrine/ORM/AbstractQuery.php#L791$query->getSingleResult())

还有不太出名的,如果找到多个结果,它将引发异常,如果未找到结果,则返回null。(请参阅此处的相关 phpdoc https://github.com/doctrine/doctrine2/blob/master/lib/Doctrine/ORM/AbstractQuery.php#L752$query->getOneOrNullResult())


答案 2

如果有多个结果,则两者都会引发异常。若要解决此问题,可以添加到查询生成器中。getSingleResult()getOneOrNullResult()setMaxResults(1)

 $firstSubscriber = $entity->createQueryBuilder()->select('sub')
        ->from("\Application\Entity\Subscriber", 'sub')
        ->where('sub.subscribe=:isSubscribe')
        ->setParameter('isSubscribe', 1)  
        ->setMaxResults(1)
        ->getQuery()
        ->getOneOrNullResult();

推荐