我读偷懒协会学说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