Doctrine INDEX BY foreign key Doctrine INDEX BY foreign key symfony symfony

Doctrine INDEX BY foreign key


Without seeing the exact composition of the entities and their relationships, it's hard to give a precise answer. Even so, if ass.article is an entity, and not the numeric article ID, the query will not work. INDEX BY must be used with an ORM column.

An example is included below:

SELECT a.id, SUM(c.visits) AS visitsFROM Customer cLEFT JOIN c.account aINDEX BY a.idGROUP BY a.id

$results will contain an associative array of entities indexed by name. To do this with a foreign key, you may have to do a join first, or use nested DQL. It is also possible that INDEX BY will not work in the exact way that you want. A workaround would look like this (includes ID as part of associative array instead of as array key):

SELECT a.id, SUM(c.visits) AS visitsFROM Customer cLEFT JOIN c.account aGROUP BY a.id

If you still cannot get this working after reading over this answer, I'd advise providing additional information about the entities and any relevant relationships.


Try like this:

$qb = $em->createQueryBuilder();$qb->select('SUM(ass.pageviews)')   ->from('YourBundle:article_stats', 'ass', 'ass.article')   ->groupBy('ass.article');$articleStats = $qb->getQuery()->getArrayResult();