In Doctrine 2 can the Fetch Mode (Eager/Lazy etc.) be changed at runtime?
Asked Answered
W

2

26

I have entities which I would like to eagerly load , and on other ocassions lazy (or even extra lazy) load.

My mappings have no fetch mode declared in my YAML- so they use the default (lazy loading).

Currently the only way to eagerly load is to by constructing the DQL manually - and I need to update this every time I add a new entity.

Ideally I would just load the root entity and the force eager loading all the associated objects. Is there any way I can do this?

If not why (is there a reason beyond it being an unimplemented feature)?

Willpower answered 4/8, 2011 at 9:53 Comment(0)
A
26

If you want to use built-in repository methods (find(), findAll()), you're probably out of luck unless you set things to eagerly load in your annotations.

You'll probably want to use the query builder (or raw DQL) in some custom repository's method to force eager loading where you want it. Yes, you'll have to update that method as you add entities, but at least you'll always know what's going on in regards to lazy/eager loading, and you'll only need to maintain it all in one place.

I suppose the reason there's not some $eagerLoad flag to find(), etc, is because those are convenience methods for simple tasks. If you wanted to add such a flag, you'd have quickly get into situations where you'd want to limit recursive eager loading by depth. You'd also probably have to start worrying about cyclical references (any bidirectional association, for instance).

Amoebic answered 4/8, 2011 at 22:18 Comment(2)
Thanks for the response. I'll the question open for a while in case there is anyone else who would like to give an opinion.Willpower
remember to add all joined tables aliases in the addSelect('alias') to include relates entities in the result.Marshland
O
24

You can use setFetchMode() method of DQL to set mode.

See the documentation: https://web.archive.org/web/20120601032806/http://readthedocs.org/docs/doctrine-orm/en/latest/reference/dql-doctrine-query-language.html

Oza answered 17/2, 2012 at 14:8 Comment(5)
note that it can only be used for Many-to-One and One-to_One associationsXylo
Because I've just lost 2 hours, in setFetchMode the first parameter must reference the current class and not the class we want to lazy or eager fetch. And the class must be indicated like AppBundle\Entity\Student (like the example display it)Frizzy
2 hours ? Count me in with 2 days ! It's crazy how annoying this is in Symfony :/Unattended
@Unattended it's Doctrine, not SymfonyThermal
That link seems to be too old. With Doctrine 2.5, I've had to use: $query->setFetchMode(MyOriginalParent::class, 'parents_alias_used_in_query', Doctrine\ORM\Mapping\ClassMetadata::FETCH_LAZY); to get it to run lazy (for the already eagerly setup entity)Augsburg

© 2022 - 2024 — McMap. All rights reserved.