2015-06-23 194 views
0

我读偷懒协会学说2,我怎么能避免以下情况:Doctrine2延迟加载

Entity dump in twig template

在这种paragraph文档中说明如何启用你的实体延迟关联。我很想如何在我的实体存储库中使用它。

到目前为止,我尝试了一些调整到实体存储库,但没有任何成功。我也试过this post,this postthis post,但他们似乎处理ManyToMany或完整的其他情况。

有人可以解释如何以及在哪里使用惰性关联来避免上面的例子吗?

由于长度限制,不相关的私有属性和getter/setter已从此代码片段中删除。

SRC /的appbundle /实体/ News.php

class News 
{ 
    /** 
    * @ORM\ManyToOne(targetEntity="AppBundle\Entity\Account", fetch="EXTRA_LAZY") 
    * @ORM\JoinColumn(name="author", referencedColumnName="id") 
    */ 
    private $author; 
} 

SRC /的appbundle /实体/存储库/ NewsRepository.php

class NewsRepository extends EntityRepository 
{ 
    /** 
    * @param $id 
    * @return mixed 
    * @throws \Doctrine\ORM\NonUniqueResultException 
    */ 
    public function findOneById($id) { 
     return $this->createQueryBuilder('a') 
        ->andWhere('a.id = :id') 
        ->setParameter('id', $id) 
        ->getQuery() 
        ->getOneOrNullResult(); 
    } 
} 

SRC /的appbundle /控制器/ NewsController .php

/** 
* @Route("/{id}", name="news_item") 
* @Method({"GET"}) 
* @Template("AppBundle:news:item.html.twig") 
*/ 
public function articleAction(Request $request, $id) 
{ 
    $news_item = $this->getDoctrine()->getRepository('AppBundle:News')->findOneById($id); 

    if (!$news_item) { 
     throw $this->createNotFoundException('No news item found by id ' . $id); 
    } 

    return array(
     'news_item' => $news_item 
    ); 
} 

的src /的appbundle /资源/视图/新闻/ item.html.twig

{% extends 'base.html.twig' %} 

{% block body %} 
    {{ dump(news_item) }} }} 
{% endblock %} 
+1

我猜'转储(news_item)'使代理解决作者。尝试查看数据库中有无转储的查询日志。 – user3557327

回答

1

你不必做任何特殊,使延迟加载。新闻无法加载作者不需要额外的延迟加载。它只是意味着你可以打电话 - >包含在集合上,而不用加载整个集合&一些其他的便利。

转储()应该能显示作者是这样的:

protected 'author' => 
    object(Proxies\__CG__\YourNamespace\YourBundle\Entity\Author) 

这并不意味着实体已经从数据库中获取。引用the docs

而不是传回给你一个真正的作者实例和集合 评论学说将为你创建代理实例。只有当你 第一次访问这些代理时,他们将通过 EntityManager并从数据库加载它们的状态。

如果您没有找回代理类,那可能是因为您已经在代码中早些时候访问了该关系。或者你已经明确地在你的查询中获取了那个实体。