2011-12-01 57 views
2

我有對象CategoryProduct關係(一對多)。我想顯示與它們相關的所有類別和對象的列表。如果我使用:Symfony2高效顯示類別和相關產品列表

$categories = $this->getDoctrine()->getRepository('AcmeZebraBundle:Category')->findAll(); 

而不是顯示此類似:

<ul> 
{% for category in categories %} 
    <li>{{ category.name }}</li> 
    <ul> 
    {% for product in category.products %} 
    <li>{{ product.name }}</li> 
    {% endfor %} 
    </ul> 
{% endfor %} 
</ul> 

它會生成每個類別的附加查詢。 我試圖將產品添加到類別 - 而不是findAll()我使用了一種方法來檢索所有對象並將它們添加到適當類別的ArrayCollection。但是這並不減少查詢次數。

public function findAllLoadProducts() 
{ 
    $categories = $this->findAll(); 
    $categortiesById = array(); 

    foreach ($categories as $category) 
    { 
     $categortiesById[$category->getId()] = $category; 
    } 

    $products = $this->getEntityManager()->getRepository('AcmeZebraBundle:Product')->findAll(); 

    foreach ($products as $product) 
    { 
     $categortiesById[$product->getCategory()->getId()]->getProducts()->add($product); 
    } 

    return $categortiesById; 
} 

回答

1

您需要將產品水合到自定義查詢中的類別。創建在同一個包來分類實體庫(或使用它,如果你已經創建了它):

<?php 
/* src/Acme/ZebraBundle/Repository/CategoryRepository.php */ 
namespace Acme\ZebraBundle\Repository; 

use Doctrine\ORM\EntityRepository; 

class CategoryRepository extends EntityRepository 
{ 
    public function retrieveHydratedCategories() 
    { 
     return $this->createQueryBuilder('c') 
        ->select('c, p') 
        ->leftJoin('c.products', 'p') 
        ->getQuery() 
        ->execute(); 
    } 
} 

然後,您可以取代您以前的「的findall」的使用此查詢:

$categories = $this->getDoctrine()->getRepository('AcmeZebraBundle:Category')->retrieveHydratedCategories(); 

leftJoin使自定義查詢獲取相同查詢中的產品,避免在模板中迭代查詢時進一步查詢。

+0

如何在不加載每個類別的全部產品收集的情況下以這種方式獲得類別產品的計數? –

相關問題