- 产品详情页获取评论数和评分rating 错误,没法取得数据,那么
this->getProduct()->getRatingSummary() 数据从哪里来的呢
//监听事件
<event name="catalog_block_product_list_collection">
<observer name="review" instance="Magento\Review\Observer\CatalogProductListCollectionAppendSummaryFieldsObserver" shared="false" />
</event>
//文件 vendor\magento\module-review\Observer\CatalogProductListCollectionAppendSummaryFieldsObserver.php
public function execute(EventObserver $observer)
{
$productCollection = $observer->getEvent()->getCollection();
$this->sumResourceFactory->create()->appendSummaryFieldsToCollection(
$productCollection,
(int)$this->storeManager->getStore()->getId(),
\Magento\Review\Model\Review::ENTITY_PRODUCT_CODE
);
return $this;
}
//文件 vendor\magento\module-review\Model\ResourceModel\Review\Summary.php
/**
* Append review summary fields to product collection
*
* @param \Magento\Catalog\Model\ResourceModel\Product\Collection $productCollection
* @param int $storeId
* @param string $entityCode
* @return Summary
* @throws \Magento\Framework\Exception\LocalizedException
*/
public function appendSummaryFieldsToCollection(
\Magento\Catalog\Model\ResourceModel\Product\Collection $productCollection,
int $storeId,
string $entityCode
) {
if (!$productCollection->isLoaded()) {
$summaryEntitySubSelect = $this->getConnection()->select();
$summaryEntitySubSelect
->from(
['review_entity' => $this->getTable('review_entity')],
['entity_id']
)->where(
'entity_code = ?',
$entityCode
);
$joinCond = new \Zend_Db_Expr(
"e.entity_id = review_summary.entity_pk_value AND review_summary.store_id = {$storeId}"
. " AND review_summary.entity_type = ({$summaryEntitySubSelect})"
);
$productCollection->getSelect()
->joinLeft(
['review_summary' => $this->getMainTable()],
$joinCond,
[
'reviews_count' => new \Zend_Db_Expr("IFNULL(review_summary.reviews_count, 0)"),
'rating_summary' => new \Zend_Db_Expr("IFNULL(review_summary.rating_summary, 0)")
]
);
}
return $this;
}
- 评论不想区分站点,也就是多语言下都显示同一批评论
需要将store id 过滤的删掉
//重写 \Magento\Review\Model\ResourceModel\Review\Collection
class Collection extends \Magento\Review\Model\ResourceModel\Review\Collection
//重写方法
public function addStoreFilter($storeId)
{
/**注释掉这些,去除store_id过滤
$inCond = $this->getConnection()->prepareSqlCondition('store.store_id', ['in' => $storeId]);
$this->getSelect()->join(
['store' => $this->getReviewStoreTable()],
'main_table.review_id=store.review_id',
[]
);
$this->getSelect()->where($inCond);
*/
return $this;
}