Search code examples
symfonydoctrine-ormdoctrinemany-to-manydql

Many-to-many relationship in doctrine2


I have a many-to-many relationship. Entities are Actor and Pys (Films and TV shows). When I want the cast of film the relation works fine (returns all the actor and actress of a film) but the problem comes when I want to retrive all the films of an actor.

This is the relation in the phpmyadmin:

enter image description here

This is the error that appear:

Key "actor" for array with keys "0" does not exist in ActorBundle:Default:actor.html.twig at line 3

Here the necessary code:

Actor's DefaultController

class DefaultController extends Controller
{
    public function peliculasAction($actId)
    {
        $em = $this->getDoctrine()->getManager();

        $peliculas = $em->getRepository('ActorBundle:Actor')->findPeliculas($actId);

        return $this->render('ActorBundle:Default:actor.html.twig', array('peliculas' => $peliculas
                ));
    }
}

ActorRepository

class ActorRepository extends EntityRepository
{
    public function findPeliculas($actId)
    {
        $em = $this->getEntityManager();

        $consulta = $em->createQuery('
            SELECT p, d, a
            FROM ActorBundle:Actor a
            JOIN a.pys p JOIN p.director d
            WHERE a.actId = :actId
            ORDER BY p.pysAnyo DESC
        ');

        $consulta->setParameter('actId', $actId);

        return $consulta->setHint(\Doctrine\ORM\Query::HINT_CUSTOM_OUTPUT_WALKER, 'Gedmo\\Translatable\\Query\\TreeWalker\\TranslationWalker')->getResult();
    }
}

actor.html.twig

(...)
{% block title %}{{ peliculas.actor.actNombre ~ ' ' ~ peliculas.actor.actApellidos }}{% endblock %}

{% block article %}
    <section class="article">
        <div id="datos-actor-director-genero">
            <strong>{{ 'Nombre:' | trans }} </strong>{{ peliculas.actor.actNombre ~ ' ' ~ peliculas.actor.actApellidos }}</br>
            <strong>{{ 'Fecha de nacimiento:' | trans }} </strong>{{ peliculas.actor.actFechaNacimiento | localizeddate('long', 'none') }}
        </div>
        <table>
            {% for pys in peliculas %}
                <tr id="fechaVotacion">
                    <td colspan="4">{{ pys.pysAnyo }}</td>
(...)

Solution

  • You are getting a doctrine collection from

    $em->getRepository('ActorBundle:Actor')->findPeliculas($actId);
    

    So in Twig, peliculas is a collection too, do a for..in or peliculas[0] if you only want the first element.

    peliculas has no key actor, only numbres (0 : first actor, 1 : second actor, etc...)