在后台分类编辑里,左侧的分类树中,每个分类ID后面的商品总数始终是该分类下所有商品的总数,和前台已展示的商品总数不一致。通过深入挖掘,发现一个核心文件的代码存在低级逻辑错误,怀疑是开源版本的一个被阉割后的人工BUG。原文件为
\vendor\magento\module-catalog\Model\ResourceModel\Category\Collection.php
先翻看到以下方法的位置:
public function loadProductCount($items, $countRegular = true, $countAnchor = true)
{
……
if ($countAnchor) {
// Retrieve Anchor categories product counts
$categoryIds = array_keys($anchor);
$countSelect = $this->getProductsCountQuery($categoryIds, (bool)$websiteId);
$categoryProductsCount = $this->_conn->fetchPairs($countSelect);
foreach ($anchor as $item) {
$productsCount = isset($categoriesProductsCount[$item->getId()])
? (int)$categoryProductsCount[$item->getId()]
: $this->getProductsCountFromCategoryTable($item, $websiteId);
$item->setProductCount($productsCount);
}
// Retrieve Anchor categories product counts
$categoryIds = array_keys($anchor);
$countSelect = $this->getProductsCountQuery($categoryIds, (bool)$websiteId);
$categoryProductsCount = $this->_conn->fetchPairs($countSelect);
foreach ($anchor as $item) {
$productsCount = isset($categoriesProductsCount[$item->getId()])
? (int)$categoryProductsCount[$item->getId()]
: $this->getProductsCountFromCategoryTable($item, $websiteId);
$item->setProductCount($productsCount);
}
……
}
}
其中 $categoriesProductsCount 这个变量是错误的,前后文响应看应该是变量 $categoryProductsCount 才能前后匹配 。这处修改好后,我们再来到以下方法的位置:
private function getProductsCountQuery(array $categoryIds, $addVisibilityFilter = true): Select
{
$categoryTable = $this->getTable(‘catalog_category_product_index’);
……
这个表名 catalog_category_product_index 也是不正确的,因为这个表名是默认STORE ID=0 的表,正常情况下这个表里不会有数据的, 所有分类商品索引只有在STORE级别才有数据,我们可以修改为:
$tableName = ‘catalog_category_product_index’;
$storeId = $this->getProductStoreId();
if (!empty($storeId)){
$tableName .= ‘_store’.$storeId;
}
$categoryTable = $this->getTable($tableName);
$storeId = $this->getProductStoreId();
if (!empty($storeId)){
$tableName .= ‘_store’.$storeId;
}
$categoryTable = $this->getTable($tableName);
具体应用的时候,可以查看自己数据库里分类商品索引对应的表名是否匹配。 在修改过这两处后,后台效果如下:


以上图示的效果,默认全局店铺下会显示分类下所有商品总数,而选择好店铺后,仅显示可展示的总数,对于有需要如此修改的需求,可以考虑复写这个核心文件,改动上文提到的两处对应代码即可。