Search code examples
doctrine-ormmany-to-many

Doctrine Optimize ManyToMany Queries


I got the following Entities:

  • A User Entity, it has OneToMany Products and OneToMany Images
  • A Product Entity that has ManyToMany Images
  • An Image Entity, having the ManyToOne to User, and the (inverted) ManyToMany Products

The Images connected to the Product are also always connected to the same User Entity too.

I want to display for the Current User the Products and their Images in a Table.

  • For this, the User is loaded by the User Provider. (1 Query)
  • Then it gets the N Products for the User (1 Query)
  • Then it ask Images joined by the ManyToMany table which Images are connected to the Products (N Queries)

The Last Queries I want to optimize somehow if able. My thought because I already know what kind of Images there will be because of the User OneToMany Relationship.

What could I do it make it better? Try to build my own Query? My own Hydrator? Maybe Caching of the Images Entities will be enough?

I tried making the Entities and their relationships Cacheable but that doesn't seems to reduce the amount of queries.


Solution

  • From what you explain:

    enter image description here

    You need to load from both user side (product and image). It can happen to load image not linked to the user (and product not linked to the user).

    Your problem com from the many to many between product and image, that will force you to load image from product and not from user.

    The solution would be to change your database to match this:

    enter image description here

    where the linked table containing all 3 foreign key has a uniq constraint on all 3. This way, you just have to load everything in 1 query from user if you use DQL or SQL.