title: How to use custom repository methods in Twig template?
body: <p>Assuming I have an entity <code>User</code> and an entity <code>Book</code> and they're both joined by <code>User.bookId = Book.id</code> (this marks a user owns a certain book, relation type oneUserToManyBook).</p>
  
  <p>If I now want to execute a performance friendly fetch with Doctrine's DQL or QueryBuilder for all <code>Books</code> a <code>User</code> has read, what is the best way to implement this in a Symfony2/Doctrine2 webapp, so that I can use them in my <code>User</code> loop in a Twig template?</p>
  
  <h2>Twig</h2>
  
  <pre><code>{% for user in users %}
     {{ user.name|e }}
         {% for address in user.getAddressesByUserId(user.getId()) %}
             {{ address.city }}
         {% endfor %}
  {% endfor %}
  </code></pre>
  
  <hr>
  
  <p>I see two approaches, but both don't lead to my target:</p>
  
  <h2>1st approach</h2>
  
  <p>Create a custom repository class <code>BookRepository</code>:</p>
  
  <pre><code>public function getBooksOwnedByUser($user_id) {
      return $em-&gt;createQuery('SELECT b.title
                               FROM MyBundle\Entity\User u,
                                    MyBundle\Entity\Book b
                               WHERE u.book_id = b.id'
                               AND u.id = :user_id)
                -&gt;setParameter('user_id', $user_id)
                -&gt;getResult();
  }
  </code></pre>
  
  <p><strong>Problem</strong>: Works fine, but I cant call <code>getBooksOwnedByUser()</code> in my Twig template (because it's not tied to the entity <code>User</code>, but to it's repository, which is a subclass of <code>Doctrine\ORM\EntityRepository</code>.</p>
  
  <hr>
  
  <h2>2nd approach</h2>
  
  <p>Execute the same query as above - not in my <code>UserRepository</code>, but directly in my <code>User</code> entity class.</p>
  
  <p><strong>Problem here:</strong> I could call this method in my Twig template, but I cannot (and should not) use the <code>EntityManager</code> in my <code>User</code> entity class.</p>