Search code examples
doctrinedoctrine-orm

How to get a Collection in Doctrine2's query results


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?


Solution

  • 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\ArrayCollection;
    
    $result = $this
        ->getEntityManager()
        ->createQueryBuilder()
        ->select('p')
        ->from('...\Player', 'p')
        ->getQuery()
        ->getResult()
    ;
    
    $players = new ArrayCollection($result);