82

What is the difference between fetch="EAGER" and fetch="LAZY" in annotation @ManyToOne in Doctrine ?

/**
 * @ManyToOne(targetEntity="Cart", cascade={"all"}, fetch="EAGER")
 */

/**
 * @ManyToOne(targetEntity="Cart", cascade={"all"}, fetch="LAZY")
 */
pmaruszczyk
  • 2,157
  • 2
  • 24
  • 49
Mohamed Ben HEnda
  • 2,686
  • 1
  • 30
  • 44

2 Answers2

120

To explain it simply, when you are loading an entity and if it has an association with one or more entities, what should doctrine do?

If the association is marked as EAGER, it will fetch and load the associated entity as well.

If the association is marked as LAZY, doctrine will create proxy objects (dummy objects) in place of the actual entity. Only when you make the first call to that associated entity (like $cart->getItems()), doctrine will fetch and load that object(s) from database. (This is the default Behaviour)

Refer: https://www.doctrine-project.org/projects/doctrine-orm/en/2.6/reference/advanced-configuration.html#association-proxies

paaacman
  • 3,012
  • 1
  • 20
  • 18
Pradeep
  • 2,469
  • 1
  • 18
  • 27
  • Btw. what is the default behaviour? I am assuming it's `LAZY`? – fritzmg Jul 29 '16 at 09:43
  • 2
    As I see it lazy loading is the default setting for doctrine: http://doctrine-orm.readthedocs.io/en/latest/tutorials/extra-lazy-associations.html – Calamity Jane Sep 29 '16 at 11:29
  • What is the default when I never write each one – A.Seddighi Oct 19 '18 at 11:38
  • 2
    The link from "Calamity Jane" doesn't work anymore, here is an updated one (for 2.6): https://www.doctrine-project.org/projects/doctrine-orm/en/2.6/tutorials/extra-lazy-associations.html#extra-lazy-associations . Quote from the link about default behavior: `Associations are marked as Lazy by default, which means the whole collection object for an association is populated the first time its accessed.` – k00ni Dec 09 '19 at 09:32
  • LAZY is the default behaviour, I think it's more faster ! – famas23 Sep 27 '20 at 21:41
  • 2
    @famas23 LAZY might be quicker, but it depends only on what you need. If you never use those associated parts, then it's surely quicker, since the hydrating has less work to do. Otherwise, if you know that you will actually use the associated parts, then it makes sense to load them right away. – userfuser May 18 '21 at 21:21
37

Additional information about the difference between them:

(fetch = "EAGER")

the associated entities will be fetched as soon as the original query target entity is loaded from doctrine. That means there is no additional SQL query on DB.

(fetch = "LAZY")

the associated entities will be fetched ONLY IF the original query target entity calls the reference method, such as $cart->getItems(). That means, there is additional SQL query on DB.

Richard Erickson
  • 2,568
  • 8
  • 26
  • 39
vikbert
  • 1,128
  • 11
  • 10