2015-06-23 106 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並從數據庫加載它們的狀態。

如果您沒有找回代理類,那可能是因爲您已經在代碼中早些時候訪問了該關係。或者你已經明確地在你的查詢中獲取了那個實體。