简体   繁体   中英

Nested queries using symfony findBy method

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM