簡體   English   中英

使用symfony findBy方法的嵌套查詢

[英]Nested queries using symfony findBy method

我有兩個實體CategoryItem 我想訪問特定類別下的所有項目。
目前,我正在執行以下操作:

  • 獲取與給定類別對應的實體
  • 通過將在上一步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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM