3

In Magento 2, I need to get details of how many reviews approved in specific product and how many average ratings percentage of specific product.

How to get this both details ?

Please help me.

Thanks.

1 Answer 1

2

You need to inject \Magento\Review\Model\ReviewFactory and \Magento\Review\Model\Rating $ratingFactory in your construct.

Add this below code in your file :

protected $_reviewFactory;
protected $_ratingFactory;

public function __construct(
..........
\Magento\Framework\App\Action\Context $context,
\Magento\Review\Model\ReviewFactory $reviewFactory,
\Magento\Review\Model\Rating $ratingFactory,
..........
) {
    ..........
    $this->_reviewFactory = $reviewFactory;
    $this->_ratingFactory = $ratingFactory;
    ..........
    parent::__construct($context);
}

public function execute()
{
    ..........
    $product_id = '1';
    $_ratingSummary = $this->_ratingFactory->getEntitySummary($product_id);
    $ratingCollection = $this->_reviewFactory->create()->getResourceCollection()->addStoreFilter(
        $this->_storeManager->getStore()->getId())->addStatusFilter(\Magento\Review\Model\Review::STATUS_APPROVED)->addEntityFilter('product', $product_id);
    $review_count = count($ratingCollection); // How many review in that specific product

    $product_rating = $_ratingSummary->getSum() / $_ratingSummary->getCount();  // Product rating in percentage
    ..........
}

Clean cache and refresh it. Hope it will helpful for you !!

3
  • There is construct must be an instance error generate. Commented Jul 4, 2018 at 18:14
  • execute this command rm -rf var/ generated/ Commented Jul 4, 2018 at 18:20
  • Happy coding !! :) Commented Jul 4, 2018 at 18:24

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.