Doctrine2 (Doctrine 2.1) 在 Symfony2 中预先加载 [英] Doctrine2 (Doctrine 2.1) eager loading in Symfony2

查看:20
本文介绍了Doctrine2 (Doctrine 2.1) 在 Symfony2 中预先加载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我的 Symfony2 项目中有两个实体:CategoryArticle(一个包含许多文章的类别).

Let's say I have two entities in my Symfony2 project : Category and Article (a category having many articles).

在我的 CategoryRepository 中,我有这个方法:

In my CategoryRepository, I have this method:

findAllDummy(){
  return $this->createQueryBuilder('c')
              ->leftJoin('c.Articles a')
              ->getQuery()->getResult();
}

如果我没记错的话,在 Symfony1.4(以及相应的 Doctrine 版本)中,返回的对象的 'articles' 属性将由相应的 Article 对象填充.现在,在 Symfony2 中,返回了 Proxy 对象.

If I remember well, in Symfony1.4 (and the corresponding version of Doctrine), the returned objects would have their 'articles' attribute filled by the corresponding Article objects. Now, in Symfony2, Proxy objects are returned.

因此,如果我遍历特定类别的文章,将执行与迭代一样多的查询.

So if I loop through a specific category's articles, As many queries as iterations will be executed.

foreach($category->getArticles() as $article){
  echo $article->getDoctrine()
               ->getRepository('')getTitle();
}

我知道这是 Doctrine2.1 的默认延迟加载行为.

I understand this is Doctrine2.1's default lazy loading behavior.

问题 1: 这是一个更好的解决方案吗?N 个查询而不是 1 个.

Question 1: how is this a better solution? N queries instead of 1.

我尝试通过执行以下操作来强制预先加载:

I tried to force eager loading by doing the following:

findAllDummy(){
  return $this->createQueryBuilder('c')
              ->leftJoin('c.articles a')
              ->getQuery()
              ->setFetchMode('Category', 'articles', 'EAGER')
              ->getResult();
}

但结果还是一样.

问题 2: 如何在 Doctrine2 中强制加载?

Question 2: how to force eager loading in Doctrine2?

推荐答案

您正在加入一个表,但没有从中选择任何内容.将 ->addSelect('a') 添加到您的查询构建器.考虑以下两个 SQL 查询以了解差异:

You're joining a table but you're not selecting anything from it. Add ->addSelect('a') to your query builder. Consider two following SQL queries to understand the difference:

SELECT a.id, a.title
FROM article a 
JOIN category c ON a.category_id = c.id 
WHERE a.id = 123;

SELECT a.id, a.title, c.id, c.name 
FROM article a 
JOIN category c ON a.category_id = c.id 
WHERE a.id = 123;

<小时>

Eager/Lazy Join 与 DQL 查询无关.它定义了使用 $articleRepository->find(123) 时应该加载的内容.

这篇关于Doctrine2 (Doctrine 2.1) 在 Symfony2 中预先加载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆