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

不羁岁月 提交于 2019-11-26 03:58:29

问题


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

回答1:


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




回答2:


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.



来源:https://stackoverflow.com/questions/26891658/what-is-the-difference-between-fetch-eager-and-fetch-lazy-in-doctrine

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!