Php Symfony2有效显示类别和相关产品列表

Php Symfony2有效显示类别和相关产品列表,php,symfony,doctrine-orm,Php,Symfony,Doctrine Orm,我有对象类别和产品关系(一对多)。我想显示所有类别和与其相关的对象的列表。如果我使用: $categories = $this->getDoctrine()->getRepository('AcmeZebraBundle:Category')->findAll(); 然后像这样显示: <ul> {% for category in categories %} <li>{{ category.name }}</li> <

我有对象
类别
产品
关系(一对多)。我想显示所有类别和与其相关的对象的列表。如果我使用:

$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>

您需要将产品添加到自定义查询中的类别中。在同一捆绑包中为您的类别实体创建存储库(如果已经创建了,则使用它):


leftJoin使自定义查询在同一查询中获取产品,从而避免在模板中迭代时进行任何进一步的查询。

如何以这种方式仅获取类别产品的数量,而不加载每个类别的整个产品集合?
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;
}
<?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();
    }
}
$categories = $this->getDoctrine()->getRepository('AcmeZebraBundle:Category')->retrieveHydratedCategories();