Doctrine join bypass lazy loading

只愿长相守 提交于 2019-12-24 00:43:56

问题


I just started exploring Symfony2 and I am amazed how many great features it has. I started doing the blog tutorial at: http://tutorial.symblog.co.uk/
but using version 2.1 instead of 2.0

My problem is that i have the following entity for Blog:

/**
 * @ORM\OneToMany(targetEntity="Comment", mappedBy="blog")
 */
protected $comments;

and the following in the Comment entity:

/**
 * @var string $blog
 *
 * @ORM\ManyToOne(targetEntity="Blog", inversedBy="comments")
 * @ORM\JoinColumn(name="blog_id", referencedColumnName="id")
 */
private $blog; 

I created the function to get the latest blogs and join the comments so i dont have to lazy load comments for each blog and avoid multiple calls to the comments table like so:

$qb = $this->createQueryBuilder('b')
            ->select('b')
            ->leftJoin('b.comments', 'c')
            ->addOrderBy('b.created', 'DESC'); 

but when i run in the twig template the result from that query as: blog.comments I got the first query to retrieve the blogs correct with the join in it but then instead of using the joined value for comments i get a call to the comments table for each blog entry? How do I bypass that functionality for that certain case but keep the relationship so i can get all comments for a blog from the view blog page?


回答1:


You also need to add the comment objects to the select results:

->select('b', 'c')


来源:https://stackoverflow.com/questions/11659145/doctrine-join-bypass-lazy-loading

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!