How can I get Detailed Rating results programatically using product id in magento 2.3.5?
I want to display it on product page.
Like this: Product: 5 stars shipping: 4 stars
Thanks!
You can get Product rating details by Product id with the use of RatingFactory
. Check the below code for this:
<?php
namespace Vendor\Module\Model;
use Magento\Framework\Model\AbstractModel;
class ProductReviews extends AbstractModel{
protected $_ratingFactory;
protected $_productFactory;
protected $_ratingFactory;
protected $_reviewFactory;
public function __construct(
\Magento\Store\Model\StoreManagerInterface $storeManager,
\Magento\Catalog\Model\ProductFactory $productFactory,
\Magento\Review\Model\RatingFactory $ratingFactory,
\Magento\Review\Model\ResourceModel\Review\CollectionFactory $reviewFactory,
) {
$this->_storeManager = $storeManager;
$this->_productFactory = $productFactory;
$this->_ratingFactory = $ratingFactory;
$this->_reviewFactory = $reviewFactory;
}
public function getReviewCollection($productId){
$collection = $this->_reviewFactory->create()
->addStatusFilter(
\Magento\Review\Model\Review::STATUS_APPROVED
)->addEntityFilter(
'product',
$productId
)->setDateOrder();
}
public function getRatingCollection(){
$ratingCollection = $this->_ratingFactory->create()
->getResourceCollection()
->addEntityFilter(
'product'
)->setPositionOrder()->setStoreFilter(
$this->_storeManager->getStore()->getId()
)->addRatingPerStoreName(
$this->_storeManager->getStore()->getId()
)->load();
return $ratingCollection->getData();
}
}
You can try this code:
public function __construct(
...
\Magento\Review\Model\ReviewFactory $reviewFactory,
\Magento\Store\Model\StoreManagerInterface $storeManager,
...
) {
...
$this->_reviewFactory = $reviewFactory;
$this->_storeManager = $storeManager;
...
}
public function getRatingSummary()
{
...
$this->_reviewFactory->create()->getEntitySummary($product, $this->_storeManager->getStore()->getId());
$ratingSummary = $product->getRatingSummary()->getRatingSummary();
return $ratingSummary;
}