Skip to content

DDC-3905: Eager fetching yields N+1 queries in *ToMany associations when using DQL #4762

@doctrinebot

Description

@doctrinebot

Jira issue originally created by user benjamin:

I have an entity with all kinds of associations:

  • OneToOne
  • OneToMany
  • ManyToOne
  • ManyToMany

I have tested using fetch="EAGER" on each of these associations, and running a DQL query against the entity.

For both OneToOne and ManyToOne, the SQL log looks like:

SELECT ... FROM Entity;
SELECT ... FROM RelatedEntity WHERE id IN (?);

Which is exactly 2 queries whatever the number of entities. This is all good.

However, for OneToMany the SQL log looks like:

SELECT ... FROM Product;
SELECT ... FROM Picture WHERE productId = ?;
SELECT ... FROM Picture WHERE productId = ?;
SELECT ... FROM Picture WHERE productId = ?;
...

And for ManyToMany the SQL log looks like:

SELECT ... FROM Product;
SELECT ... FROM Category t0 INNER JOIN ProductCategory ... WHERE ProductCategory.productId = ?;
SELECT ... FROM Category t0 INNER JOIN ProductCategory ... WHERE ProductCategory.productId = ?;
SELECT ... FROM Category t0 INNER JOIN ProductCategory ... WHERE ProductCategory.productId = ?;
...

Eager loading OneToMany and ManyToMany results in N+1 queries, so there's no point eager loading them at all.

Is this a bug, or a known limitation?

What prevents Doctrine from using a WHERE IN () and a single, second query?

Metadata

Metadata

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions