让我们说在我的索引页面中,我想显示我的所有类别,子类别以及每个类别的产品数量。
当我有很多对象时,查询计数会变得很大。通过使用Querybuilder获取所有类别,我已经将计数减少了三倍。但是,当我在树枝上显示所有内容时,有很多查询。
{% for category in categories %}
{% if app.request.getLocale() == 'en' %}
<li class="subMenu" style="cursor:pointer;"><a> {{ category.name }}</a>
<ul>
{% for subcategory in category.children %}
<li><a href="{{ path('products_in_categories', {id: subcategory.id, name: subcategory.name}) }}">{{ subcategory.name }} [{{ countSubProducts(subcategory.id)}}]</a></li>
{% endfor %}
<li><a href="{{ path('products_in_categories', {id: category.id, name: category.name}) }}">{{ "category.show_all" | trans }} [{{ countCatProducts(category.id)}}]</a></li>
</ul>
</li>
{% else %}
<li class="subMenu" style="cursor:pointer;"><a> {{ category.nameEs }}</a>
<ul>
{% for subcategory in category.children %}
<li><a href="{{ path('products_in_categories', {id: subcategory.id, name: subcategory.nameEs}) }}">{{ subcategory.getNameEs }} [{{ countCatProducts(subcategory.id)}}] </a></li>
{% endfor %}
<li><a href="{{ path('products_in_categories', {id: category.id, name: category.nameEs}) }}">{{ "category.show_all" | trans }} [{{ countSubProducts(category.id)}}]</a></li>
</ul>
</li>
{% endif %}
{% endfor %}
正如你所看到的,我正在做各种for循环,因为我不知道任何其他方式来显示每个类别/子类别。
这些循环正在进行大量的查询......我怎样才能减少所有这些?有可能吗?
答案 0 :(得分:0)
您可以这样做:
{% set myname = "nameEs" %}
{% if app.request.getLocale() == 'en' %}
{% set myname = "name" %}
{% endif %}
{% for category in categories %}
<li class="subMenu" style="cursor:pointer;"><a> {{ attribute(category, myname) }}</a>
<ul>
{% for subcategory in category.children %}
<li><a href="{{ path('products_in_categories', {id: subcategory.id, name: attribute(subcategory, myname)}) }}">{{ attribute(subcategory, myname) }} [{{ countSubProducts(subcategory.id)}}]</a></li>
{% endfor %}
<li><a href="{{ path('products_in_categories', {id: category.id, name: attribute(category, myname)}) }}">{{ "category.show_all" | trans }} [{{ countCatProducts(category.id)}}]</a></li>
</ul>
</li>
{% endfor %}