I was reading about lazy associations in Doctrine 2 and how I could avoid the following situation:
In this paragraph in the documentation is explained how to enable lazy associations for your entity. I am missing how I could use this within my entity repository.
So far I tried some adjustments to the entity repository but without any success. I also tried this post, this post and this post but they seem to handle ManyToMany or a complete other situation.
Could somebody explain how and where to use lazy association to avoid the above example?
Irrelevant private properties and getters/setters have been removed from this code snippets due to the length.
<kbd>src/AppBundle/Entity/News.php</kbd>
class News
{
/**
* @ORM\ManyToOne(targetEntity="AppBundle\Entity\Account", fetch="EXTRA_LAZY")
* @ORM\JoinColumn(name="author", referencedColumnName="id")
*/
private $author;
}
<kbd>src/AppBundle/Entity/Repositories/NewsRepository.php</kbd>
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();
}
}
<kbd>src/AppBundle/Controller/NewsController.php</kbd>
/**
* @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
);
}
<kbd>src/AppBundle/Resources/views/news/item.html.twig</kbd>
{% extends 'base.html.twig' %}
{% block body %}
{{ dump(news_item) }} }}
{% endblock %}