How to get a Collection in Doctrine2's query results

mkraemer picture mkraemer · Nov 19, 2011 · Viewed 36.3k times · Source

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

Simplified snippet:

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

The returned object is an array of Player.

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?

Answer

chriswoodford picture chriswoodford · Nov 23, 2011

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

e.g.

use Doctrine\Common\Collections;

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

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