Doctrine QueryBuilder indexBy on joined class - p is already defined Error Doctrine QueryBuilder indexBy on joined class - p is already defined Error symfony symfony

Doctrine QueryBuilder indexBy on joined class - p is already defined Error


The attribute indexBy only apply to the entity you are currently selecting, as you have guessed (and AFAIK); so in your case you could only index by u.id.

This makes sense to me, since indexing from other entity really mess up the returned results. The only situation in which you'll get proper result is when:

  • all the join from the main entity and the "target" indexBy entity are one-to-one;
  • all the join are INNER JOIN;
  • the indexBy column of the resultset is unique.

In every other case you loose some instance reference during hydration.

In your example, you are using LEFT JOIN: what will happen to all entities without product? All discarded, so the LEFT JOIN would have worker like an INNER JOIN. Also, your workaround suggest that you want to combine entities with the same index, but this is not how Doctrine work: in Doctrine an indexBy column MUST be unique. See the official docs for more info.

Note that you could indexBy p.id in your JOIN clause, but this has different meaning. It means that when hydrating the UserIngredients instances, the collection of product should be indexed by id.

So, my suggestion is to follow one of this two solution:

  • give up on Doctrine indexBy, and use your workaraound;
  • If you have the inverse association Product -> UserIngredients, use Product as the main entity of the query (the from clause, and first to appear in select), and then index by p.id.

Which one to use depends on your business logic, but I generally prefer the second solution, since the first generate multiple-level array, which are better represented by entity relations.

Hope this help! :)