问题
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