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.
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 !!