0

I am using a joined query to extract user data together with the role data from an associated table. The query is extracting the data, but I cannot work out how to extract a specific element from the join.

query from repo:

public function loadAllUsers()
{
    $q = $this
        ->createQueryBuilder('u')
        ->select('u', 'r')
        ->leftJoin('u.roles', 'r')
        ->addOrderBy('u.username', 'ASC');

    return $q->getQuery()->getResult();
}

my twig template section:

            {% for user in users %}
                <tr>
                    <td>{{ user.id }}</td>
                    <td>{{ user.username }}</td>
                    <td>{{ user.firstname }}</td>
                    <td>{{ user.lastname }}</td>
                    <td>{{ user.email }}</td>
                    <td>{{ user.lastLogged.date }}</td>
                    <td>{{ user.roles.name }}</td> <!-- insert role name in here -->
                    <td>{{ user.isactive }}</td>
                </tr>
            {% endfor %}

output from a twig dump of the user object sent to the template

users {#264 ▼
  -id: 1
  -username: "admin"
  -password: "$2y$12$9f76e741dd03a517a5207OkX/gjsP3mif2RxJIs00WyVUj4c3jYPS"
  -firstname: "Matt"
  -lastname: "HB"
  -isActive: true
  -email: "[email protected]"
  -lastLogged: DateTime {#262 ▶}
  -salt: "9f76e741dd03a517a5207b91476079c7"
  -roles: PersistentCollection {#280 ▼
    -snapshot: array:1 [ …1]
    -owner: users {#264}
    -association: array:20 [ …20]
    -em: EntityManager {#121 …10}
    -backRefFieldName: "users"
    -typeClass: ClassMetadata {#265 …}
    -isDirty: false
    -initialized: true
    -coll: ArrayCollection {#281 ▼
      -_elements: array:1 [▼
        0 => roles {#288 ▼
          -id: 6
          -name: "super_admin"
          -role: "ROLE_SUPER_ADMIN"
          -users: PersistentCollection {#289 ▶}
        }
      ]
    }
  }
}

Ive tried the following lines to no avail. I need the role name for the user.

{{ user.roles.name }}
{{ user.roles.coll.name ]}

1 Answer 1

1

You need to use a loop in your twig template to iterate over the individual roles like this:

{% for role in user.roles %}
    {{ role.name }}
{% endfor %}
Sign up to request clarification or add additional context in comments.

4 Comments

thanks for the reply. i might not have explained myself very well. Ill alter my question to clarify.
Still, according to the dump, you have multiple roles per user. That is the reason why you cannot just print one of them but have to use a loop.
ah true! I forgot theres a third table that contains the relationship. Ill have to do another join. Many thanks
No thanks required, better accept the answer, if it solved your problem. :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.