Question

Here I want a Product Review based on Product id.

An object containing something like:

review_id
product_image
date
author
price
product_id
rating
product_name
comment
Was it helpful?

Solution

This is example to get product review by Product ID

By Objectmanager

$productId = '2'; // Product ID
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$product = $objectManager->create("Magento\Catalog\Model\Product")->load($productId);
$storeManager = $objectManager->get('Magento\Store\Model\StoreManagerInterface');
$currentStoreId = $storeManager->getStore()->getId();
$rating = $objectManager->get("Magento\Review\Model\ResourceModel\Review\CollectionFactory");

$collection = $rating->create()->addStoreFilter(
            $currentStoreId
        )->addStatusFilter(
            \Magento\Review\Model\Review::STATUS_APPROVED
        )->addEntityFilter(
            'product',
            $productId
        )->setDateOrder();

print_r($collection->getData()); //Get all review data of product

By Factory Method

  protected $productRepository; 
  protected $_reviewCollection; 

  public function __construct(
      ...
      \Magento\Catalog\Api\ProductRepositoryInterface $productRepository,
      \Magento\Review\Model\ResourceModel\Review\CollectionFactory $reviewCollection,
      ...
  ) {
      ...
      $this->productRepository = $productRepository;
      $this->_reviewCollection = $reviewCollection;
      ...
  }

  public function getCollection()
  {
    $productId = 2;
    $product = $this->productRepository->getById($productId);
    $collection = $this->_reviewCollection->create()
      ->addStatusFilter(
        \Magento\Review\Model\Review::STATUS_APPROVED
      )->addEntityFilter(
      'product',
        $productId
      )->setDateOrder();

      print_r($collection->getData()); //Get all review data of product
  }

OTHER TIPS

Try below code to get Product reviews by Id

<?php
$id= 12; // product id
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$product = $objectManager->create("Magento\Catalog\Model\Product")->load($id);
$rating = $objectManager->get("Magento\Review\Model\ResourceModel\Review\CollectionFactory");
$collection = $rating->create()
        ->addStatusFilter(
            \Magento\Review\Model\Review::STATUS_APPROVED
        )->addEntityFilter(
            'product',
             $id
        )->setDateOrder();
echo "<pre>";
print_r($collection->getData());
?>
Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange
scroll top