Doctrine2 预先加载运行多个查询而不是 1 [英] Doctrine2 eager loading runs multiple queries instead of 1
问题描述
我将 Symfony2 与 Doctrine2(最新版本)一起使用,并定义了这种关系:
I'm using Symfony2 with Doctrine2 (latest versions) and have this relation defined:
/**
* @ORMOneToMany(targetEntity="Field", mappedBy="event", fetch="EAGER")
* @ORMOrderBy({"name" = "ASC"})
*/
protected $fields;
关系的另一端定义为:
/**
* @ORMManyToOne(targetEntity="Event", inversedBy="fields", fetch="EAGER")
* @ORMJoinColumn(nullable=false, onDelete="CASCADE")
*/
protected $event;
执行fetchOnyById"时,Doctrine 运行 2 个查询.1 获取对象本身,1 获取相关字段.我希望这是一个连接,但它不是.
When doing a "fetchOnyById", Doctrine runs 2 queries. 1 to fetch the object itself and 1 for the related fields. I would expect this to be a join, but it isn't.
在控制器中完成后,我将对象传递给 twig.在那里我再次检索字段作为对象的属性.这会导致运行另一个查询以再次检索字段.
When done in the controller, I pass my object to twig. There I retrieve the fields again as a property of the object. This causes another query to be run to retrieve the fields again.
显然我做错了什么,因为我希望只运行 1 个查询,而实际运行 3 个.
Clearly I'm doing something wrong, as I would expect only 1 query to be run and 3 are actually run.
推荐答案
我相信发生这种情况的原因是因为您正在获取实体,而不是特定查询.Doctrine 的想法是您正在获取对象,而不是与数据库交互,而是与对象资源交互,就好像它们都像存储实体一样关联/引用.如果您需要像您所描述的那样的查询,最好使用 DQL,但此时您不会获取创建的实体,而是获得自定义结果.
I believe the reason this is occurring is because you're fetching entities, not a specific query. The idea of Doctrine is that you're fetching objects, not interacting with a database but an object resource as if they're all associated/referenced like stored entities. If you need a query like you're describing you would be better off using DQL but at that point you're not fetching entities created, you're getting a custom result.
我希望这是有道理的.
基本上,您使用的默认关联是获取关联对象,而不是连接查询.
Basically the default association you're using is fetching associated objects not a joined query.
这篇关于Doctrine2 预先加载运行多个查询而不是 1的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!