Alex Rivera | Logout

How to get a Collection in Doctrine2's query results

Asked 2011-11-19T18:08:12.223
41

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?

Edit
Report

1 Answer

1

Since you're selecting only 'p' objects (and no individual column or aggregate values) and you're using getResult() for the hydration mode, your query should be returning pure objects rather than an array.

My best guess is that the problem has to do with the shorthand syntax you're using to build the query. The first thing I'd try is writing out the query "long form" like this:

$em = $this->getEntityManager();
$qb = $em->createQueryBuilder();

$qb->select('p')
   ->from('...\Player', 'p');

$query = $qb->getQuery();
$players = $query->getResult();

I would have guessed that your shorthand approach would be fine, but I've found Doctrine to be kind of finicky when it comes to method chaining.

There are a couple other things to consider depending on how simplified your snippet is. But in my experience, the query written as shown will return Player objects.

answered 2011-11-19T21:50:22.497

Your Answer