Reputation: 137
I'm currently using a createQueryBuilder to join 2 entities (category and blog) that are One ToMany and ManyToOne.
I've recently added a tag entity to blog (ManyToMany/ManyToMany) and would like to join this in the same query.
How would I do this?
current query:
public function getBlogs($limit = null)
{
$qb = $this->createQueryBuilder('b')
->select('b, c')
->leftJoin('b.category', 'c')
->addOrderBy('b.created', 'DESC');
return $qb->getQuery()
->getResult();
}
tag entity:
/**
* @ORM\ManyToMany(targetEntity="Blog", mappedBy="tags")
*/
protected $blogs;
public function __construct()
{
$this->blogs = new ArrayCollection();
}
blog entity:
/**
* @ORM\ManyToOne(targetEntity="Category", inversedBy="blogs")
* @ORM\JoinColumn(name="category_id", referencedColumnName="id")
*/
protected $category;
/**
* @ORM\ManyToMany(targetEntity="Tag", inversedBy="blogs")
* @ORM\JoinColumn(name="tag_id", referencedColumnName="id")
*/
protected $tags;
public function __construct()
{
$this->tags = new ArrayCollection();
}
category entity:
/**
* @ORM\OneToMany(targetEntity="Blog", mappedBy="category")
*/
protected $blogs;
public function __construct()
{
$this->blogs = new ArrayCollection();
}
Upvotes: 1
Views: 103
Reputation: 6268
This should be pretty easy by doing the following:
public function getBlogs($limit = null)
{
$qb = $this->createQueryBuilder('b')
->select('b, c, tag')
->leftJoin('b.category', 'c')
->leftJoin('b.tags', 'tag')
->addOrderBy('b.created', 'DESC')
;
// ...
}
Upvotes: 1