S
S
saorityan2017-01-16 15:29:53
symfony
saorityan, 2017-01-16 15:29:53

How to vary loading types (greedy/lazy) in different cases for the same Doctrine model?

example: there are products, product categories, product suppliers
On the category list page, I only need categories
On the category edit page, I need categories and all related products (link for simplicity: one category to many products)
On the category page for the user, I need all categories with preloaded providers in those categories.
The problem is that if I make products eager loading in categories, then products will be selected on other pages, although they are not needed everywhere.
And if you do not choose greedily, then for 10 categories there will be 11 queries in the database.
How best to sort out what pages to choose for.?
After experience with eloquent, I want an analogue of with.
Surely such problems have already been solved with the doctrine.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Dmitry MiksIr, 2017-01-16
@miksir

I prefer to solve these questions through DQL.
Those. in the first case SELECT c FROM Category c;
In the second case SELECT p, c FROM Product p JOIN p.category;
Etc. https://doctrine-orm.readthedocs.io/en/latest/refe...
Also in case of DQL you can use setFetchMode
https://doctrine-orm.readthedocs.io/en/latest/refe...

D
Denis, 2017-01-16
@prototype_denis

You need to load not categories with suppliers or products, but child entities by category.

$category = $entityManager->getReference(Category::class, $categoryId);

$productRepository->findProductsByCategory(Category $category /*, ...*/);
$productRepository->findProductsByCategories(ArrayCollection $categories /*, ...*/);

As a result, instead of 10 requests for each, there will be only one with all the data.
Also, besides fetch="EAGER" there are also named queries.
docs.doctrine-project.org/en/latest/reference/nati... just so as not to produce methods for trivial requests.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question