我讀偷懶協會學說2,我怎麼能避免以下情況:Doctrine2延遲加載
在這種paragraph文檔中說明如何啓用你的實體延遲關聯。我很想如何在我的實體存儲庫中使用它。
到目前爲止,我嘗試了一些調整到實體存儲庫,但沒有任何成功。我也試過this post,this post和this 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 %}
我猜'轉儲(news_item)'使代理解決作者。嘗試查看數據庫中有無轉儲的查詢日誌。 – user3557327