0

I'm trying to get each individual review rating on a product, but currently I am only able to return the product's overall average rating.

Here is what I have so far to build my collection of reviews in my block file:

<?php
namespace Company\Module\Block;

class Index extends \Magento\Framework\View\Element\Template
{
  protected $reviewCollection;

  public function __construct(
    \Magento\Framework\View\Element\Template\Context $context,
    \Magento\Review\Model\ResourceModel\Review\CollectionFactory $reviewCollection,
    array $data = []
  ){
    $this->_reviewCollection = $reviewCollection;
    parent::__construct($context, $data);
  }

  public function getReviews($product)
  {
    $reviews = $this->_reviewCollection->create()->addStatusFilter(\Magento\Review\Model\Review::STATUS_APPROVED)->addEntityFilter('product',$product->getId())->setDateOrder();
    return $reviews;
  }
}

And then in my phtml file, I'm calling my block:

$reviews = $block->getReviews($product); // $product assigned earlier in code
if (count($reviews) > 0) {
  foreach ($reviews->getItems() as $review) {
    //get individual review summary here
  }
}

Not sure if I'm using the correct resource model in my block, maybe I need to build the collection of reviews differently?

1 Answer 1

0

Figured this out with the following:

<?php
namespace Company\Module\Block;

class Index extends \Magento\Framework\View\Element\Template
{
  protected $voteCollection;

  public function __construct(
    \Magento\Framework\View\Element\Template\Context $context,
    \Magento\Review\Model\ResourceModel\Rating\Option\Vote\CollectionFactory $voteCollection,
    array $data = []
  ){
    $this->_voteCollection= $voteCollection;
    parent::__construct($context, $data);
  }

public function getReviewRating($reviewId)
  {
    $rating = $this->_voteCollection->create();
    $rating->addRatingInfo()->addOptionInfo()->addRatingOptions()->addFieldToFilter('review_id',$reviewId);
    return $rating->getData();
  }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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