使用Doctrine NativeQuery获取单行结果 [英] Get single row result with Doctrine NativeQuery

查看:436
本文介绍了使用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() code>,如果找到多个结果,或者没有找到结果,它将抛出异常。 (请参阅相关phpdoc这里 https://github.com/doctrine/ doctrine2 / blob / master / lib / doctrine / ORM / AbstractQuery.php#L802

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

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#L763)

这篇关于使用Doctrine NativeQuery获取单行结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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