[英]Prevent Doctrine from fetching related entities
I have a User
entity which has One-To-Many association with Account
entity: 我有一个与Account
实体具有一对多关联的User
实体:
/**
* @var Account[]
*
* @ORM\OneToMany(
* targetEntity="AppBundle\Account",
* mappedBy="user",
* cascade={"persist", "remove"},
* orphanRemoval=true
* )
*/
protected $accounts;
I'm fetching a list of users and joining accounts to them: 我正在获取用户列表并将他们加入帐户:
$builder = $this->getEntityManager()->createQueryBuilder()
->select('U')
->from('Model:User', 'U')
->leftJoin('U.accounts', 'A')
;
However, when I'm trying to access fetched accounts of the user I can see that Doctrine are making additional queries to the database to fetch accounts for each user. 但是,当我尝试访问该用户的访存帐户时,我可以看到Doctrine正在对数据库进行其他查询以为每个用户访存帐户。
foreach ($users as $user) {
foreach ($user->getAccounts() as $account) {
// This triggers additional Doctrine query.
var_dump($account->getId());
}
}
I'm running this code as a batch job and I want to achieve maximum performance by pre-loading users with accounts and not to issue additional queries later. 我正在以批处理方式运行此代码,我想通过向用户预加载帐户来实现最佳性能,并且以后不发出其他查询。
Why Doctrine makes additional queries and how to prevent this? 为什么教义会进行其他查询,以及如何防止这种情况?
I've tried to use fetch="EXTRA_LAZY"
option for OneToMany
association, but without any luck, the results are the same. 我尝试对OneToMany
关联使用fetch="EXTRA_LAZY"
选项,但没有任何运气,结果是相同的。
You must add the account
data to the select statement: 您必须将account
数据添加到选择语句中:
$builder = $this->getEntityManager()->createQueryBuilder()
->select('U')
->from('Model:User', 'U')
->addSelect('A')
->leftJoin('U.accounts', 'A')
;
Regarding the fetch, fetch="EXTRA_LAZY"
is for loading less data. 关于提取, fetch="EXTRA_LAZY"
用于装载较少的数据。 You probably want fetch="EAGER"
which will automatically load related entities. 您可能想要fetch="EAGER"
,它将自动加载相关的实体。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.