0

noob alert;

I have Post and Tag Entities like this:

Post.php

 /**
 * Many posts can have many tags. This is the owning side.
 * @ORM\ManytoMany(targetEntity="Tag", inversedBy="posts")
 * @ORM\JoinTable(name="post_tag")
 */
 protected $tags;

Tag.php

 /**
 * Many tags can belong to many different posts. This is the inverse side
 * @ORM\ManytoMany(targetEntity="Post", mappedBy="tags")
 */
 protected $posts;

Now, I want to query all posts with their tags.

For that, I'm using queryBuilder in my Repository and successfully able to retrieve results.

$query = $this->createQueryBuilder('P')
        ->select('P.title, T.name')
        ->leftJoin('P.tags', 'T')
        ->where('P.id = 1')
        ->getQuery()
        ->execute();

But as you can possibly imagine, this query fetches duplicates. So, if I had two tags for a post, there would be two similar posts inside the array.

Output

array(
  array(title=>'Post One', name=>'php'),
  array(title=>'Post One', name=>'python'),
)

Is there a doctrine way to turn these tags into an array collection and stuff this back into the final post array.

Sumit Wadhwa
  • 2,825
  • 1
  • 20
  • 34
  • Possible duplicate of [How to select distinct query using symfony2 doctrine query builder?](https://stackoverflow.com/questions/7188219/how-to-select-distinct-query-using-symfony2-doctrine-query-builder) – malarzm Dec 14 '18 at 19:20
  • @malarzm thanks i'm gonna give it shot though i'm not sure if it's actually related – Sumit Wadhwa Dec 14 '18 at 19:28
  • Sorry I might have jumped the gun with that flag. If DISTINCT is not working for entities try grouping by post's id. – malarzm Dec 14 '18 at 19:45
  • can you maybe post an example, sorry not an experienced doctrine user.. – Sumit Wadhwa Dec 14 '18 at 19:49
  • @malarzm I'm not sure if it's even possible with doctrine. i'm gonna stick to raw sql for now. `GROUP_CONCAT` working fine for me in this matter. or perhaps there's something i might be missing nd will probably get in the future. thanks anyways – Sumit Wadhwa Dec 14 '18 at 20:06

0 Answers0