Reputation: 4490
I have two entities Category
and Item
. I want to access all items under a particular category.
Presently, I'm doing this as follows:
category
selected in previous step as a parameter to findBy
method.Here is my code:
public function indexAction($category)
{
$em = $this->getDoctrine()->getManager();
$category = $em -> getRepository('AppBundle:Category')
-> findOneBy(array(
"name" => $category
));
$entities = $em->getRepository('AppBundle:Item')
->findBy(array(
'category' => $category
));
return array(
'entities' => $entities,
'title' => $category
);
}
Am I doing right? In this case I need two separate queries. Is there any efficient method?
Upvotes: 1
Views: 2062
Reputation: 478
Does your Category
entity have a OneToMany relationship with Item
(http://symfony.com/doc/current/book/doctrine.html#entity-relationships-associations)?
If so, you can set up a join and use that to get all the Items corresponding to a Category by defining a new method in the Category
entity class. Something like:
public function findOneByNameJoinedToItems($category)
{
$query = $this->getEntityManager()
->createQuery(
'SELECT c, i FROM AppBundle:Category c
JOIN c.item i
WHERE c.name = :name'
)->setParameter('name', $category);
try {
return $query->getSingleResult();
} catch (\Doctrine\ORM\NoResultException $e) {
return null;
}
}
See here for more: http://symfony.com/doc/current/book/doctrine.html#joining-related-records
Upvotes: 1