我正在尝试使用doctrine2执行查询,并且需要它来返回集合对象。
简化代码段:
$players = $this->getEntityManager()
->createQueryBuilder()
->select('p')
->from('...\Player', 'p')
->getQuery()
->getResult();
返回的对象是Player的数组。
关于query result formats的信息说:
结果是对象的简单集合(纯)或对象嵌套在结果行(混合)中的数组。
结果类型取决于什么以及如何获得集合对象?
答案 0 :(得分:57)
getResult()始终返回一个数组。如果你想要一个集合,你必须将getResult()返回的数组传递给Doctrine的ArrayCollection
e.g。
use Doctrine\Common\Collections;
$result = $this->getEntityManager()
->createQueryBuilder()
->select('p')
->from('...\Player', 'p')
->getQuery()
->getResult();
$players = new Collections\ArrayCollection($result);
答案 1 :(得分:1)
由于您只选择'p'对象(并且没有单独的列或聚合值)并且您正在使用getResult()进行水合模式,因此您的查询应该返回纯对象而不是数组。
我最好的猜测是,问题与您用于构建查询的简写语法有关。我要尝试的第一件事就是写出这样的查询“long form”:
$em = $this->getEntityManager();
$qb = $em->createQueryBuilder();
$qb->select('p')
->from('...\Player', 'p');
$query = $qb->getQuery();
$players = $query->getResult();
我猜想你的速记方法会很好,但是我发现在方法链接方面,Doctrine有点挑剔。
还有一些其他事项需要考虑,具体取决于您的代码段的简化程度。但根据我的经验,如图所示编写的查询将返回Player对象。
答案 2 :(得分:1)
要返回一个对象而不是数组,你必须使用“Partial Objects”。
这里是经过测试的代码示例https://stackoverflow.com/a/12044461/1178870