Symfony2高效显示类别和相关产品列表
我有对象 Category
和 Product
关系(一对多)。我想显示所有类别和与其相关的对象的列表。如果我使用:
$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;
}
I've got object Category
and Product
relation (one-to-many). I want to display list of all categories and objects related to them. If I use:
$categories = $this->getDoctrine()->getRepository('AcmeZebraBundle:Category')->findAll();
And than display this like that:
<ul>
{% for category in categories %}
<li>{{ category.name }}</li>
<ul>
{% for product in category.products %}
<li>{{ product.name }}</li>
{% endfor %}
</ul>
{% endfor %}
</ul>
It will generate additional query for each category.
I tried to add products to categories - instead of findAll()
I used a method which retrieves all objects and add them to ArrayCollection
of an appropriate category. But this does not reduce number of queries.
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;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您需要将产品合并到自定义查询中的类别中。在同一个包中为您的类别实体创建一个存储库(如果您已经创建了它,则使用它):
然后您可以使用此查询代替之前的“findall”:
leftJoin 使自定义查询在同一查询中获取产品,当您在模板中迭代它们时避免任何进一步的查询。
You need to hydrate the products to the categories in a custom query. Create a Repository for your Category entity in the same bundle (or use it if you already created it):
You can then use this query in place of your previous "findall":
The leftJoin makes the custom query fetch the products in the same query, avoiding any further query when you iterate on them in your template.