A. Grima
A. Grima

Reputation: 57

How to group Entity by other Entity with Symfony

I'am working on Symfony project using Doctrine

So I have 3 Entities :

A project has severals activities, and an activity has several Categories as well

I'm trying to get all activities, groupped by categories of a project.

What is the proper way of doing that?

I tried with a QueryBuilder, but it seems that you can't group by with an other entity, only with a value (tell me if I'm wrong)

$q = $repo->createQueryBuilder('a')
        ->leftJoin('a.project', 'p')
        ->leftJoin('a.categories', 'category')
        ->where('p.id = ?1')
        ->setParameter(1, $projectId)
        ->groupBy('category.id')
        ->getQuery();
    return $q->getResult();

EDIT What I really need, is to display a list of categories with according activities inside

-Category1
     -Activity1
     -Activity2
     -Activity3
-Category2
     -Activity3
     -Activity4
-Category4
     -Activity1
     -Activity2
     -Activity3
     -Activity4
     -Activity5

Is my way to do this good and my code wrong? Or am I wrong everywhere ?

Thanks a lot for your time !

Upvotes: 4

Views: 211

Answers (1)

Alessandro Lai
Alessandro Lai

Reputation: 2274

You should fetch and iterate over categories, not actions:

$q = $categoryRepo->createQueryBuilder('c')
    ->leftJoin('c.actions', 'a')
    ->leftJoin('a.project', 'p')
    ->where('p.id = ?1')
    ->setParameter(1, $projectId)
    ->getQuery();
return $q->getResult();

And then, in your template (are you using Twig?)

{% for category in categories %}
 - {{ category }}
    {% for action in category.actions if action.project.id = 1 %}
     - {{ action }}
    {% endfor %}
{% endfor %}

Upvotes: 1

Related Questions