-1

I have some difficulties in DQL (and SQL !). I always write simple querys but now I need something more specific and I don't know how to do it.

I have an entity User in OneToMany with my entity Program which is in OneToMany with my entity Exercice which is in OneToMany with my Reps.

I would like to know for an specific User all the reps is done. What would be the best way to do it ?

Micka Bup
  • 391
  • 1
  • 9

1 Answers1

0
        $this->createQueryBuilder('user')
        ->select('rep')
        ->join('user.programs', 'program')
        ->join('program.exercices', 'exercice')
        ->join('exercice.reps', 'rep')
        ->getQuery()
        ->getResult();

Explication:

This code must be in your repository. The user repository one.

        $this->createQueryBuilder('user')
        is equivalent to
        $this->_em->createQueryBuilder()
        ->select('user')
        ->from('user')

You can override the select with the second line:

            ->select('rep')

Then do the join as described in your question.

programs must be the entity attribute you defined in user to join program Same goes for exercices and reps. They correspond to the inversed side of the relationship.

The second paramter in join() function is the alias. It can be anything you want. You use aliases in select and in the next join()

Florent Cardot
  • 1,400
  • 1
  • 10
  • 19
  • I just did exactyly what you said but I've got this error : `[Semantical Error] line 0, col -1 near 'SELECT rep FROM': Error: Cannot select entity through identification variables without choosing at least one root entity alias.` – Micka Bup Jan 13 '21 at 14:51
  • This mean you did not called it from the user repository. try the second one: $this->_em->createQueryBuilder() ->select('rep') ->from('user')->.... – Florent Cardot Jan 13 '21 at 18:17
  • I created in my UserRepository a findAllRepsByUser($user) and I'v tried as u suggested but it did'nt work. Even with the second one I get an error – Micka Bup Jan 13 '21 at 19:15
  • Ok I found it. Instead of `->select('rep')` I use `->select('rep.number')` Thx for the help – Micka Bup Jan 13 '21 at 19:29