16

Is it possible to use index by with the doctrine 2 query builder, and if so what is the proper syntax?

John
  • 465
  • 1
  • 4
  • 17

6 Answers6

44

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.

cmenning
  • 630
  • 5
  • 10
7

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.

ken
  • 4,886
  • 4
  • 30
  • 26
4

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...

Simon Kerr
  • 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
3

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.

BrokenPixel
  • 73
  • 1
  • 8
0

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.

Working with Indexed Associations

webDEVILopers
  • 1,886
  • 1
  • 21
  • 35
-1

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.

Kees Schepers
  • 2,248
  • 1
  • 20
  • 31