Is it possible to use index by with the doctrine 2 query builder, and if so what is the proper syntax?
6 Answers
Beginning with 2.2, you can now include INDEX BY in your from statement. If you are adding a from clause,
$qb->from($class, $alias, $indexBy);
If you already have a from clause that you want to replace, then you can replace it with:
$qb->add('from', new Expr\From($class, $alias, $indexBy), false);
There's an open pull request to add it to the Repository's createQueryBuilder function as well, so hopefully this will get added soon.

- 630
- 5
- 10
-
Hey, I'm writing from 2015, and it's not there yet :-( – zerkms Apr 01 '15 at 00:53
For an update. You can do something like this.
$qb = $entityManager->createQueryBuilder();
$qb->from($repository->getClassName(), 'a', 'a.id');
$qb->select(a);
$result = new ArrayCollection($qb->getQuery()->getResult());
As a result, array collection will contain properly indexed elements.

- 4,886
- 4
- 30
- 26
Here's one solution when using querybuilder, using manual injection of the index by clause -
(do you querybuilder statement)
$q = $q->getQuery()->setDQL(str_replace('WHERE', 'INDEX BY yourIndexValue WHERE', $q->getDQL()));
This seems to work for me...

- 566
- 1
- 4
- 3
-
I realise this is a very old answer, but I would just like to point out that this won't work for queries that don't have any WHERE clause. – rpkamp Feb 03 '16 at 11:30
The proper syntax and the simplest would be:
$enityManager->getRepository('AppBundle:Entity')->createQueryBuilder('entity', 'entity.name')->getQuery()->getResult();
This would index the result by Entity name field.

- 73
- 1
- 8
You can also use a default INDEX BY of a foreign key e.g. "yourIndexValue_id" directly in your mapping:
/**
* @ORM\OneToMany(targetEntity="Bar", mappedBy="foo", indexBy="bar_id")
*/
protected $bars;
Unfortunately it does not seem to be documented that you have to use the name of the column of the foreign key itself.

- 1,886
- 1
- 21
- 35
Yes that's possible, using the query builder. A small example, let's assume we want to index by t.someField. Watch the third argument in from method.
<?php
$query = $em->createQueryBuilder()
->select('t.somefield', 't.someOtherField')
->setFrom('Entity\Table', 't', 't.someField')
->getQuery()
$results = $query->getArrayResult();
//your result will look something like:
$results['somefieldvalue'] = array(array('somefield' => 'value', 'someOtherField' => 'test'));
?>
This should work in Doctrine 2.1 at least. In Doctrine 2.0 it's not supported yet. In Doctrine 2.0 it's only supported when you specify it with DQL.

- 2,248
- 1
- 20
- 31
-
2With Doctrine 2.1.0-DEV, I use `$qb->add('from', 'Entity\Table t INDEX BY t.id');` – Maxence Feb 18 '12 at 13:30