Doctrine 2 and Symfony2, Using INDEX BY in Query Builder

It can be useful to get the resulting array from a query using the object id as key. This can be achieved in PDO by using the PDO::FETCH_NAMED and PDO::FETCH_NUM fetch styles and Doctrine offers this as well. When using the query builder all you have to do is to use the third parameter on the “from” part:

 

The third parameter to the ‘from’ method tells doctrine to use the id property on the User object as the array key when returning the results. In most cases you’ll want the indexBy column to have a unique constraint as the results may be unpredictable otherwise.

One thought on “Doctrine 2 and Symfony2, Using INDEX BY in Query Builder

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.