[英]Nested queries using symfony findBy method
我有兩個實體Category
和Item
。 我想訪問特定類別下的所有項目。
目前,我正在執行以下操作:
category
選擇的category
作為參數傳遞給findBy
方法來獲取所有項。 這是我的代碼:
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
);
}
我做對了嗎? 在這種情況下,我需要兩個單獨的查詢。 有什么有效的方法嗎?
您的Category
實體與Item
是否具有OneToMany關系( http://symfony.com/doc/current/book/doctrine.html#entity-relationships-associations )?
如果是這樣,可以通過在Category
實體類中定義一個新方法來建立連接並使用該連接來獲取與某個Category對應的所有Items。 就像是:
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;
}
}
有關更多信息,請參見此處: http : //symfony.com/doc/current/book/doctrine.html#joining-related-records
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.