You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Shopware 6:自定义列表区块显示子分类商品数量的问题

解决Shopware自定义区块中子分类商品数量显示问题

问题原因

导航树返回的Category实体默认没有预加载products关联关系,所以直接通过treeItem.category.products获取会返回null。

解决方案

方案1:使用自带的商品统计字段(推荐)

Shopware的Category实体自带productCount字段,直接调用即可获取该分类下的商品数量:

{% block sw_cms_block_display_categories %}
    <div class="subcategory-block-container">
        {% set currentCategoryId = page.header.navigation.active.id %}
        {% set currentCategoryChildren = page.header.navigation.getChildren(currentCategoryId).tree %}

        {% for treeItem in currentCategoryChildren %}
            {% set category = treeItem.category %}
            {% set name = category.translated.name %}
            <a href="{{ category_url(category) }}" class="custom-category-item"> 
                {{ name }} ({{ category.productCount }})
            </a>
        {% endfor %}
    </div>
{% endblock %}

方案2:通过Repository手动查询商品数量

如果productCount不符合需求(比如需要包含子分类商品数等自定义逻辑),可以通过CategoryRepository查询完整的关联数据:

{% block sw_cms_block_display_categories %}
    <div class="subcategory-block-container">
        {% set currentCategoryId = page.header.navigation.active.id %}
        {% set currentCategoryChildren = page.header.navigation.getChildren(currentCategoryId).tree %}
        {% set categoryRepository = services.repository_factory.create('category') %}

        {% for treeItem in currentCategoryChildren %}
            {% set categoryId = treeItem.category.id %}
            {% set criteria = shopware.criteria() %}
            {% do criteria.addAssociation('products') %}
            {% set category = categoryRepository.search(criteria, context).get(categoryId) %}
            
            {% set name = category.translated.name %}
            {% set productCount = category.products ? category.products.total : 0 %}
            <a href="{{ category_url(category) }}" class="custom-category-item"> 
                {{ name }} ({{ productCount }})
            </a>
        {% endfor %}
    </div>
{% endblock %}

注意:这种方法会增加数据库查询次数,大量子分类场景下建议配合缓存优化。

内容的提问来源于stack exchange,提问作者Mirko Benini

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.24 01:28:18