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:
/**
* @ORM\OneToMany(targetEntity="Field", mappedBy="event", fetch="EAGER")
* @ORM\OrderBy({"name" = "ASC"})
*/
protected $fields;
该关系的另一面定义为:
The other side of the relation is defined as:
/**
* @ORM\ManyToOne(targetEntity="Event", inversedBy="fields", fetch="EAGER")
* @ORM\JoinColumn(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屋!