求助:如何在Magento 1.9 CE中获取当前分类的平均评分
获取Magento 1.9 CE当前分类平均评分的解决方案
Hey there! I see you're new to Magento and stuck on getting the average rating for your current category in 1.9 CE. Let's break down how to solve this properly—your existing code is on the right track but missing the key parts to fetch and calculate ratings efficiently.
先说说你现有代码的小问题
- 用
addAttributeToSelect('*')加载所有产品属性太浪费性能了,我们只需要产品ID就能关联评分数据 - 没有把产品集合和Magento的评分存储表关联起来,所以没法直接从产品里拿到评分信息
- 没过滤掉禁用/不可见的产品,这些产品的评分不该被算进分类平均里
高效的完整解决方案代码
与其循环遍历每个产品和它们的评论(大分类下会很慢),我们可以直接用Magento内置的review_entity_summary表——这里预存了每个产品的平均评分,效率高很多。代码如下:
// 获取当前分类 $currentCategory = Mage::getModel('catalog/layer')->getCurrentCategory(); if (!$currentCategory->getId()) { echo "未找到当前分类"; return; } // 只获取分类下启用且可见的产品ID(提升性能) $productCollection = Mage::getModel('catalog/product')->getCollection() ->addAttributeToSelect('entity_id') ->addCategoryFilter($currentCategory) ->addFieldToFilter('status', Mage_Catalog_Model_Product_Status::STATUS_ENABLED) ->addFieldToFilter('visibility', array('in' => Mage_Catalog_Model_Product_Visibility::VISIBILITY_BOTH)); $productIds = $productCollection->getAllIds(); if (empty($productIds)) { echo "该分类下没有产品"; return; } // 获取当前店铺下这些产品的评分汇总 $ratingSummaryCollection = Mage::getModel('review/review_summary') ->getCollection() ->addFieldToFilter('entity_type', Mage_Review_Model_Review::ENTITY_PRODUCT) ->addFieldToFilter('entity_pk_value', array('in' => $productIds)) ->addFieldToFilter('store_id', Mage::app()->getStore()->getId()); // 计算平均评分 $totalRating = 0; $ratedProductCount = 0; foreach ($ratingSummaryCollection as $summary) { $rating = $summary->getRatingSummary(); if ($rating > 0) { // 只统计有实际评分的产品 $totalRating += $rating; $ratedProductCount++; } } $averageRating = 0; $averageStars = 0; if ($ratedProductCount > 0) { $averageRating = $totalRating / $ratedProductCount; $averageStars = $averageRating / 20; // 转换为5星制(Magento评分汇总用0-100的数值) echo "当前分类平均评分:" . number_format($averageStars, 1) . "星(" . number_format($averageRating, 1) . "/100)"; } else { echo "该分类下产品暂无评分"; }
代码细节说明
- 性能优化:只加载必要的产品ID,用预计算的评分汇总表替代遍历所有评论
- 结果准确:过滤了启用且可见的产品(和用户前台看到的一致),并且按当前店铺统计评分(不同店铺的评分可能不同)
- 容错处理:提前处理了无分类、无产品、无评分的情况,避免报错
内容的提问来源于stack exchange,提问作者AznYouth
相关产品推荐
相关产品推荐

