1

Usually when querying in a custom repository class, I use something like this :

SELECT * FROM BundleName:Entity

But how do I do for associative entity ?

I have an entity "Ticket" and an entity "Tag". It's a ManyToMany relation.

In phpMyAdmin, I've got a ticket_tag associative table but how do I get it with Doctrine ?

Thank you

Tibo
  • 197
  • 2
  • 15
  • How did you configure your relations in doctrine ? If it is a real ManyToMany, why do you need those associative objects ? You should have a getter on both sides to get the related objects or use DQL query to get either one by specific conditions. – Jeroen Aug 07 '18 at 12:09
  • I have got getters on both sides, but I want to do more than that. Let's say I want to get the number of tickets for each tag. I don't want to loop on ALL tickets (ticket->getTags()). If my user has got 10k tickets for exemple. – Tibo Aug 07 '18 at 12:13
  • My working SQL is the following : SELECT tag.id, tag.name, count(tt.ticket_id) FROM ticket_tag tt, savBundle:Tag tag WHERE tag.id = tt.tag_id GROUP BY tag.id, tag.name. So ideally, I would want to know how to get my ticket_tag table with doctrine – Tibo Aug 07 '18 at 12:16
  • Getting a scaler value is a [completely different question](https://stackoverflow.com/questions/9214471/count-rows-in-doctrine-querybuilder/9215880#9215880). You probably need to be a bit more specific and perhaps visit the [dql section](https://www.doctrine-project.org/projects/doctrine-orm/en/2.6/reference/query-builder.html) of the docs. – Cerad Aug 07 '18 at 12:17
  • In https://stackoverflow.com/questions/9214471/count-rows-in-doctrine-querybuilder/9215880#9215880], we use the bundle entity from symfony, but I want to use a table that is NOT an entity in my symfony project. I can't just do the BundleName:EntityName thing – Tibo Aug 07 '18 at 12:33
  • No idea what you are asking for. Use sql if you need to fetch stuff from an unmapped table. But I don't see how you can have an associative entity that is not an entity. In other words, update your question with your actual question and maybe someone can help. – Cerad Aug 07 '18 at 12:46

1 Answers1

4

You should use createQueryBuilder to handle your custom query requirement, in case if you are having a valid relationship over entities. for example: Inside ticket repository you should handle like this, if you want to do more operations then you should learn more from here: https://symfony.com/doc/3.3/doctrine/repository.html

$query = $this->createQueryBuilder('t')
     ->select('count(t.id) as total_ticket, tag.id as tagId')
     ->leftJoin('t.tags', 'tag')
     ->groupBy('tag.id')
;

return $query->getQuery()->getResult();
Ashutosh Rai
  • 458
  • 1
  • 7
  • 14
  • 1
    to see/learn more relevant methods related createQueryBuilder please have look here https://www.doctrine-project.org/projects/doctrine-orm/en/2.6/reference/query-builder.html – Ashutosh Rai Aug 07 '18 at 12:20