Doctrine2查询返回数组而不是集合

Doctrine2查询返回数组而不是集合

问题描述:

我正在尝试使用doctrine2执行查询,并需要它返回一个集合对象。

I am trying to execute a query using doctrine2 and need it to return a collection object.

简化的代码段:

$players = $this->getEntityManager()
    ->createQueryBuilder()
    ->select('p')
    ->from('...\Player', 'p')
    ->getQuery()
    ->getResult();

返回的对象是一个数组。

The returned object is an array.

有关查询结果的信息格式表示结果是对象(纯)的简单集合或对象嵌套在结果行(混合)中的数组。结果类型取决于什么,如何实现获取集合对象?

The information on query result formats says "The result is either a plain collection of objects (pure) or an array where the objects are nested in the result rows (mixed)". On what does the result type depend and how can I achieve getting a collection object?

getResult()总是返回一个数组。如果你想要一个集合,你必须将getResult()返回的数组传递给Doctrine的ArrayCollection

the getResult() always returns an array. If you want a collection, you must pass the array that is returned by getResult() to Doctrine's ArrayCollection

例如

use Doctrine\Common\Collections;

$result = $this->getEntityManager()
    ->createQueryBuilder()
    ->select('p')
    ->from('...\Player', 'p')
    ->getQuery()
    ->getResult();

$players = new Collections\ArrayCollection($result);