How can programatically get product rating and review in product collection in Magento 2.
-
first to set enable rating from admin side here– Nikhil waghelaAug 10, 2017 at 11:10
-
it was already enabled..i want to get the rating programatically– srgAug 11, 2017 at 4:15
-
please confirm whether you are looking for ratnigs and reviews collection by using sku– Nagendra KodiSep 1, 2017 at 8:54
2 Answers
You can just pass the product object and get the rating summary for specific product.
protected $_reviewFactory;
public function __construct(
...
\Magento\Review\Model\ReviewFactory $reviewFactory,
...
) {
...
$this->_reviewFactory = $reviewFactory;
...
}
public function getRatingSummary()
{
...
$this->_reviewFactory->create()->getEntitySummary($product, $this->_storeManager->getStore()->getId());
return $product->getRatingSummary()->getRatingSummary();
}
-
i got the product rating...but how can i get the product review by customers..?– srgSep 5, 2017 at 4:39
You can use below code to get products reviews and rating summary
$sku = 'test-product';
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$product = $objectManager->create("Magento\Catalog\Model\Product")->loadByAttribute('sku', $sku); //use load($producID)
$storeManager = $objectManager->get('Magento\Store\Model\StoreManagerInterface');
$currentStoreId = $storeManager->getStore()->getId();
Rating summary
$reviewFactory = $objectManager->create('Magento\Review\Model\Review');
$reviewFactory->getEntitySummary($product, $currentStoreId);
$ratingSummary = $product->getRatingSummary()->getRatingSummary();
Reviews
$review = $objectManager->get("Magento\Review\Model\ResourceModel\Review\CollectionFactory");
$collection = $review->create()->addStoreFilter(
$currentStoreId
)->addStatusFilter(
\Magento\Review\Model\Review::STATUS_APPROVED
)->addEntityFilter(
'product',
$product->getId()
)->setDateOrder();
print_r($collection->getData());