0

How can programatically get product rating and review in product collection in Magento 2.

3
  • first to set enable rating from admin side here Aug 10, 2017 at 11:10
  • it was already enabled..i want to get the rating programatically
    – srg
    Aug 11, 2017 at 4:15
  • please confirm whether you are looking for ratnigs and reviews collection by using sku Sep 1, 2017 at 8:54

2 Answers 2

0

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();
}
1
  • i got the product rating...but how can i get the product review by customers..?
    – srg
    Sep 5, 2017 at 4:39
0

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());

Your Answer

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

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