Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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)?

like image 725
calumbrodie Avatar asked Aug 04 '11 09:08

calumbrodie


2 Answers

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).

like image 128
timdev Avatar answered Sep 23 '22 01:09

timdev


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

like image 23
atorkhov Avatar answered Sep 24 '22 01:09

atorkhov