您可能已经知道,评论和评级在每个在线业务中都发挥着重要作用,尤其是在 Magento 2 平台上运行的业务,因为它直接关系到商店的声誉以及客户的购买决策。

因此,在今天的帖子中,我将为您提供在 Magento 2 中获取评论和评级集合的最简单方法。

如何获取评论、评分集合

要获得产品评论、评级集合,您需要创建一个ProductReviews.php文件。遵循这条路径Example/HelloWorld/Model/ProductReviews.php,以下是您将如何做到的。

<?php

namespace Example\HelloWorld\Model;
use Magento\Framework\Model\AbstractModel;
class ProductReviews extends AbstractModel{

    protected $_ratingFactory;
    protected $_productFactory;
    protected $_ratingFactory;
    protected $_reviewFactory;

    public function __construct(
            \Magento\Store\Model\StoreManagerInterface $storeManager,
            \Magento\Catalog\Model\ProductFactory $productFactory,
            \Magento\Review\Model\RatingFactory $ratingFactory,
            \Magento\Review\Model\ResourceModel\Review\CollectionFactory $reviewFactory,
        ) {
            $this->_storeManager = $storeManager;
            $this->_productFactory = $productFactory;
            $this->_ratingFactory = $ratingFactory;
            $this->_reviewFactory = $reviewFactory;
        }

    public function getReviewCollection($productId){
        $collection = $this->_reviewFactory->create()
        ->addStatusFilter(
            \Magento\Review\Model\Review::STATUS_APPROVED
        )->addEntityFilter(
            'product',
            $productId
        )->setDateOrder();

    }

    public function getRatingCollection(){
        $ratingCollection = $this->_ratingFactory->create()
        ->getResourceCollection()
        ->addEntityFilter(
            'product' 
        )->setPositionOrder()->setStoreFilter(
            $this->_storeManager->getStore()->getId()
        )->addRatingPerStoreName(
            $this->_storeManager->getStore()->getId()
        )->load();

        return $ratingCollection->getData();
    }

}