Doctrine lazy loading on manyToMany.
I'm using Application\Sonata\ClassificationBundle\Entity\Tag
in my blog(post).
/**
* @var string
*
* @ORM\ManyToMany(targetEntity="\Application\Sonata\ClassificationBundle\Entity\Tag", cascade={"persist"} )
* @ORM\JoinTable( name="blog__post_tag" ,
* joinColumns={ @ORM\JoinColumn( name="blog_post_id", referencedColumnName="id" )},
* inverseJoinColumns={ @ORM\JoinColumn( name="tag_id", referencedColumnName="id" )}
* )
*/
private $tags;
Working code:
$q = $this->createQueryBuilder('p')
->select('p')
->innerJoin('p.tags', 't')
->where('t = :name')->setParameter('name', $tag)
->andWhere('p.isActive = :active')->setParameter('active', TRUE)
->orderBy('p.id', 'DESC');
return $q->getQuery();
From this output query i use tags in twig. So i have to select post and tags. If i update the code to :
$q = $this->createQueryBuilder('p')
->select('p', 't')
->innerJoin('p.tags', 't')
->where('t = :name')->setParameter('name', $tag)
->andWhere('p.isActive = :active')->setParameter('active', TRUE)
->orderBy('p.id', 'DESC');
return $q->getQuery();
I get only one tag.
INFO :
- Working code uses more db query (1 more query).
- Updated code works (no more query). But in result i get only one tag for all post.
Example :
- "My First post " has tags ['one','two','three'].
- "My Second post " has tags ['two'].
When i use first query. Works fine. But the doctrine lazy load code for tags. I get output for (query1) two = "My First post " has tags ['one','two','three']. , "My Second post " has tags ['two'].
When i use second query. The output for (query2) two = "My First post " has tags ['two']. , "My Second post " has tags ['two'].
I need all tags from the post. Currently i get only one tag form the post.