I'm quite a beginner at Symfony 2 and Doctrine 2. I have two models a Blog
post and Comment
. They are related to each other by blog_id
FK inside comment
table.
I just want to create a simple method that takes a blog id, Retrieves that blog and related comments. Instead of doing another query in lazy-loading the related comments.
Here's what i tried :
<?php
namespace Blogger\BlogBundle\Entity\Repository;
use Doctrine\ORM\EntityRepository;
class BlogRepository extends EntityRepository
{
public function getBlogWithComments($id)
{
$query = $this->getEntityManager()->createQuery('
SELECT b, c
FROM BloggerBlogBundle:Blog b
WHERE b.id = :id
JOIN b.id c
WHERE b.id = c.blog');
$query->setParameter("id", $id);
return $query->getResult();
}
}
I'm really a beginner at Doctrine 2. I usually use Query Builder, But i have no idea how to make a join using it. So Tried it in DQL, Couldn't figure it out either.
It gives me this syntax error whenever i try to call getBlogWithComments
method:
[Syntax Error] line 0, col 80: Error: Expected end of string, got 'JOIN'
All what i want to know is that, How to write JOIN statements using Query Builder and DQL ? Knowing that documentation is not that helpful unfortunately.
A JOIN
with DQL is done by referencing the relationship between the entities and it only needs to go one way. What I mean is b.comment c
is all that is needed, there is no need for referencing c.blog
.
public function getBlogWithComments($id)
{
return $this->getEntityManager()
->createQuery('
SELECT b, c
FROM BloggerBlogBundle:Blog b
JOIN b.comment c
WHERE b.id = :id
')
->setParameter("id", $id)
->getResult();
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.