title: Symfony2: Get roles of groups in user entity but avoid query inside entity
body: <p>My <code>User</code> entity implements <code>UserInterface</code> and therefore provides the <code>getRoles()</code> method. In my system a <code>User</code> can belong to multiple <code>Group</code>s. A group can have multiple roles. Thus a user's roles can be determined by collecting all groups and merging the lists of those groups' roles. The same thing is possible with <a href="https://github.com/FriendsOfSymfony/FOSUserBundle" rel="nofollow">FOSUserBundle</a>.</p>
  
  <p>The easiest algorithm would be:</p>
  
  <pre><code>public function getRoles()
  {
      $roles = $this-&gt;roles;
      foreach ($this-&gt;getGroups() as $group) {
          $roles = array_merge($roles, $group-&gt;getRoles());
      }
      return array_unique($roles);
  }
  </code></pre>
  
  <p>I think this solution is problematic because it will scale badly. For each group a new query has to be executed, so the amount of queries depends on the amount of groups.</p>
  
  <p>Usually I'd solve this by defining a single query which collects all groups of the user and joins the groups' roles. That would require calling the <code>UserRepository</code> (or directly building a Doctrine query) from the <code>User</code> entity and I believe that is a bad practice.</p>
  
  <p>So how could I avoid this bad practice while maintaining the performance advantages of a single join query?</p>
  
  <p>(This time it was very hard for me to find a question title that fits. I'm not sure whether there are other simililar situations but I don't think so, because usually I would provide such method in the repository itself. In this case the <code>UserInterface</code> requires it to be in the entity)</p>