Reputation: 3356
I am new to Symfony and going through the book on Symfony website and to be exact this section.
In the first example the following function is used to join the two tables product
and category
and it is making perfect sense
public function findOneByIdJoinedToCategory($id)
{
$query = $this->getEntityManager()
->createQuery(
'SELECT p, c FROM AcmeStoreBundle:Product p
JOIN p.category c
WHERE p.id = :id'
)->setParameter('id', $id);
try {
return $query->getSingleResult();
} catch (\Doctrine\ORM\NoResultException $e) {
return null;
}
}
What I dont understand is the second example,
public function showAction($id)
{
$product = $this->getDoctrine()
->getRepository('AcmeStoreBundle:Product')
->findOneByIdJoinedToCategory($id);
$category = $product->getCategory();
}
When in first function two tables are being joined then what is the purpose of $category = $product->getCategory();
in second function?
The problem I have with this code $category = $product->getCategory();
is if i leave it as it is it works fine IF the product has any assigned category, but if the product does not have any assigned category i get the error
Call to a member function getCategory() on a non-object
If i remove the code $category = $product->getCategory();
and access the product where no category is assigned then I get the error that i should 404
I will really appreciate if someone can explain to me why is this happening.
Upvotes: 0
Views: 347
Reputation: 2263
The line $category = $product->getCategory(); is useless if you don't need this variable $category. if you didn't JOIN in the query this line $category = $product->getCategory(); will make another query to database to get the Category.
As for the twig {{product.category.name}} if there was no JOIN and no relation it will, the category will be null, it is not related to $category = $product->getCategory(); code.
Upvotes: 1