1

I have two entities Category and Item. I want to access all items under a particular category.
Presently, I'm doing this as follows:

  • Get entity corresponding to given category
  • Get all Items by passing 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?

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.