Using Doctrine, how do you access Entity methods from a EntityRepository?-Collection of common programming errors

In the Symfony “Book”, they talk about Entities with references to other entities. Like, in my case, if I have a “Post” Entity with many “Comment” Entities referencing it, I can load the Post by its ID and then do $post->getComments().

The Comment are lazy-loaded, it seems, and I would have to either go one-by-one through them, loading each (which is clearly wrong) or load them all in a separate query (which I could do, but I don’t know where, specifically, to put that query). The Book, however, suggests: “Of course, if you know up front that you’ll need to access both objects, you can avoid the second query by issuing a join in the original query.” It recommends I add a method to my (currently-empty) postRepository class. I do, and it looks like this:

public function loadPostFull($pid)
{
    return $this->getEntityManager()
        ->createQuery('
            SELECT p, c FROM BUNDLENAME:Post p
            JOIN p.comments c
            WHERE p.id = :id')
        ->setParameter('id', $pid);
    try {
        return $query->getSingleResult();
    } catch (\Doctrine\ORM\NoResultException $e) {
        return null;
    }
}

And then in my controller I do:

$fullPost = $this->getDoctrine()
            ->getRepository('BUNDLENAME:Post')
            ->loadPostFull($id);
$id = $fullPost->getId();

But my simple request for $id gives a “Fatal error: Call to undefined method Doctrine\ORM\Query::getId()”. I know the controller is finding the loadPostFull method correctly, because if I typo the name it will fail there. It’s just not returning a proper Post entity. If I change the controller to call ->find($id) instead of ->loadPostFull($id) I can use all the internal methods of the Post id.

The manual seems to indicate I can do that! What’s wrong?

  1. I believe you have a typo :). Look at the first line of your code. You have a return statement! So you return the Query object and try { } catch() { } is never reached. You should put it like this:

    $query = $this->getEntityManager()
        ->createQuery('
            SELECT p, c FROM BUNDLENAME:Post p
            JOIN p.comments c
            WHERE p.id = :id')
        ->setParameter('id', $pid);
    try {
        return $query->getSingleResult();
    } catch (\Doctrine\ORM\NoResultException $e) {
        return null;
    }
    

Originally posted 2013-11-27 12:01:56.