I'm having some trouble pulling up relationed objects from my database using Doctrine2 in Symfony2. I have a custom repository with the following function:
public function getOrder($id) {
$DQL = 'SELECT request, orderer
FROM OrderRequestBundle:OrderRequest request
JOIN request.orderer orderer
WHERE request.id = :id';
$query = $this->getEntityManager()->createQuery($DQL)
->setParameter('id', $id)
->setMaxResults(1);
return $query->getResult();
}
...but for some reason when I run this function I get back a Proxy object for an OrderRequest object rather than a real instance of OrderRequest, am I missing something? It seems that Doctrine2 loves lazy-loading and I can't seem to get it up off its ass and fetch objects for me.
UPDATE: I'm attempting to simply display the information in a Twig template with the code below:
$order = $this->getDoctrine()
->getRepository('OrderRequestBundle:OrderRequest')
->getOrder($id);
return $this->render('OrderRequestBundle:Admin:view.html.twig', array('order' => $order));
Where Twig calls information about the 'order' variable as so:
{{ order.quantity }}
...but I just end up with this error:
Item "quantity" for "Array" does not exist in "OrderRequestBundle:Admin:view.html.twig" at line 5
UPDATE
Given your edit, the problem isn't proxy objects at all, it's how you're using your $query object.
$query->getResult()
will return an array of results. In an instance like this where you're limiting the result set to a max of 1 row, it'll return an array with one entry, but still an array. Twig chokes on this when trying to use accessor methods, naturally.
What you'll want to do is use $query->getSingleResult()
instead. Note that Doctrine will throw a non-unique result exception if the query returns more than one row, so you need to be sure to use it with setMaxResults(1)
like you're doing if the query can possibly return multiple results.
END UPDATE
From the documentation on reference proxies:
Here $item is actually an instance of the proxy class that was generated for the Item class but your code does not need to care. In fact it should not care. Proxy objects should be transparent to your code.
Emphasis theirs. Proxies should be transparent to your code, and exist to improve performance where possible; however, if you have a pressing need to eager-load part of the query, you can either set the fetch mode in your entity configuration file, or check out this section of the docs:
$query = $em->createQuery("SELECT u FROM MyProject\User u");
$query->setFetchMode("MyProject\User", "address", "EAGER");
$query->execute();