What is the difference between fetch="EAGER" and fetch="LAZY" in doctrine

Mohamed Ben HEnda picture Mohamed Ben HEnda · Nov 12, 2014 · Viewed 55.4k times · Source

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")
 */

Answer

Pradeep picture Pradeep · Nov 12, 2014

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.

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