Doctrine2一对一关系自动加载查询 [英] Doctrine2 one-to-one relation auto loads on query
问题描述
我的查询如下所示:
我的用户实体有一对一的关系,如下所示:
My user entity has a one-to-one relation that looks like this:
/**
* @var UserProfile
*
* @ORM\OneToOne(targetEntity="UserProfile",mappedBy="user")
*/
private $userProfile;
每当我查询选择多个用户对象时,它会为每个用户创建一个附加的select语句来查询对于UserProfile数据,即使我没有通过get方法访问它。我并不总是需要UserProfile数据,我当然不希望每次显示一个用户列表时加载这些数据。
Anytime I make a query to select multiple user objects, it creates an additional select statement per user to query for the UserProfile data even though I am not accessing it through a get method. I don't always need the UserProfile data, and I certainly don't want to load this data every single time I'm displaying a list of users.
任何想法为什么这些查询在运行时执行?
Any idea why these queries are executed at run time?
推荐答案
这里是解决方案解释细节:
Here is solutions explain with details :
https://groups.google.com/forum/#!topic/ doctrine-user / fkIaKxifDqc
映射中的fetch是一个提示,即如果可能的话
原则做到这一点,但如果不可能的话,显然没有。
延迟加载的代理在技术上并不总是可能的。
不可能的情况是:
"fetch" in the mapping is a hint, that is, if it is possible Doctrine does that, but if its not possible, obviously it does not. Proxying for lazy-loading is simply not always possible, technically. The situations where its not possible are:
1)从反向到所有方一对一(仅出现在
双向one-一对一关联)。前提条件a)以上不能
得到满足。 2)与层次结构的一对一/多对一关联,并且
目标类具有子类(不是类层次结构中的叶)。
前提条件b)无法满足
1) one-to-one from inverse to owning side (appears only in bidirectional one-to-one associations). Precondition a) above can not be met. 2) one-to-one/many-to-one association to a hierarchy and the targeted class has subclasses (is not a leaf in the class hierarchy). Precondition b) above can not be met.
在这些情况下,代理在技术上是不可能的。
In these cases, proxying is technically not possible.
您可以选择避免此n + 1问题:
Your options to avoid this n+1 problem:
1)通过DQL获取加入:select c,ca from Customer join c.cart ca。
单个查询但是加入,但是,加入一对一关联是
相对便宜。
1) fetch-join via DQL: "select c,ca from Customer join c.cart ca". Single query but join, however, joins on to-one associations are relatively cheap.
2)强制部分对象。没有其他查询,但
也没有lazy-load:$ query-> setHint(Query :: HINT_FORCE_PARTIAL_LOAD,
true)
2) force partial objects. No additional queries but also no lazy-load: $query->setHint(Query::HINT_FORCE_PARTIAL_LOAD, true)
3)如果替代结果格式(即getArrayResult())是
足够用于一个用例,这些也避免了这个问题。
3) if an alternative result format (i.e. getArrayResult()) is sufficient for a use-case, these also avoid this problem.
本杰明有一些关于自动批处理的想法这些加载到
避免n + 1个查询,但这并不改变代理是
并不总是可能的事实。
Benjamin had some ideas about automatic batching of these loads to avoid n+1 queries but this does not change the fact that proxying is not always possible.
这篇关于Doctrine2一对一关系自动加载查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!