3

I am fetching associated objects through 3 tables (“User”,” Client”,” Account”). “User” has a one-to-many relationship to “Client”, “Client” has a one-to-many relationship to “Account”. I fetch all the “Accounts” for one specific “User” using the following code:

$qb = $this->getDoctrine()->getManager()->createQueryBuilder()
->select('u, c, a')
->from('AcmeUserBundle:User', 'u')
->leftJoin('u.clients', 'c')
->leftJoin('c.accounts', 'a')
->where('u.id = :id');

$user = $qb->getQuery()
->setParameter('id', $id)
->getOneOrNullResult();

I pass the $user array to a TWIG template but I can’t find the correct loop to retrieve all the accounts contained in the “$user” array. What is the best way to achieve this? What should be done in the Controller vs. what should be done in TWIG? Could you give me an example of code that would work? I looked at this answer but did not manage to apply the given guidance How to get values from a multidimensional array in Twig?

Cœur
  • 37,241
  • 25
  • 195
  • 267
Bastien
  • 596
  • 1
  • 11
  • 30
  • Please share what you have tried so far in twig. – cb0 Mar 15 '15 at 15:53
  • I would try `{% for account in user.accounts %}{{ account.id }}{% endfor %}` Replace `id` by an existing property of `accounts`. – A.L Mar 15 '15 at 16:02
  • Twig's for loops work like PHP. You can nest them and loop through a properties' contents. – bassplayer7 Mar 15 '15 at 16:30
  • In TWIG, all attempts to use 'client' or 'account' trigger the error "message "variable 'client' (or 'account') does not exist". I have been trying to work on a PHP solution as well. However, the getResults() method does not return an array of variables but an array of object. Thus, I get "Error: Cannot use object of type Acme\UserBundle\Entity\User as array" when I try to work on the $user array in my controller. – Bastien Mar 15 '15 at 20:45

1 Answers1

2

$user isn't an array its an single object its probably why you can't loop over it. You can try instead

$users = $qb->getQuery()
->getlResults();

$twig->render('template.twig', array('users' => $users));

and in template.twig

{% for user in users %}
{{ dump(user) }}
{% endfor %}

More about dump: http://twig.sensiolabs.org/doc/functions/dump.html

and then probably:

{% for user in users %}
<h1>User: {{ user.id }}</h1>
list clients:<br/>
    {% for client in user.clients %}
    <div>
       <h2>Client: {{ client.id }}</h2>
       {{ dump(client) }}
       List accounts:<br/>
       {% for account in user.accounts %}
       <div>
          <h3>Account: {{ account.id }}</h3>
          {{ dump(account) }}
       </div>
       {% endfor %}
    </div>
    {% endfor %}
{% endfor %}
Xesenix
  • 2,418
  • 15
  • 30