使用 Doctrine NativeQuery 获取单行结果 [英] Get single row result with Doctrine NativeQuery
问题描述
我正在尝试使用 Doctrine 获取从本机查询返回的单行.这是我的代码:
I'm trying to get a single row returned from a native query with Doctrine. Here's my code:
$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();
最后一行返回一个玩家列表,但我只想要一个结果.我该怎么做?
That last line returns a list of players but I just want one result. How do I do that?
推荐答案
您可以使用 $query->getSingleResult()
,如果找到多个结果会抛出异常,或者如果没有找到结果.(请参阅此处的相关 phpdoc https://github.com/doctrine/doctrine2/blob/master/lib/Doctrine/ORM/AbstractQuery.php#L791)
You can use $query->getSingleResult()
, which will throw an exception if more than one result are found, or if no result is found. (see the related phpdoc here https://github.com/doctrine/doctrine2/blob/master/lib/Doctrine/ORM/AbstractQuery.php#L791)
还有一个不太出名的$query->getOneOrNullResult()
,如果找到多个结果,它将抛出异常,如果没有找到结果,则返回 null.(请参阅此处的相关 phpdoc https://github.com/doctrine/doctrine2/blob/master/lib/Doctrine/ORM/AbstractQuery.php#L752)
There's also the less famous $query->getOneOrNullResult()
which will throw an exception if more than one result are found, and return null if no result is found. (see the related phpdoc here https://github.com/doctrine/doctrine2/blob/master/lib/Doctrine/ORM/AbstractQuery.php#L752)
这篇关于使用 Doctrine NativeQuery 获取单行结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!