Magento 2 Get Review, Rating Collection

As you might have already known, review and rating play an important role in every online business, especially those which run on the Magento 2 platform as it related directly to the reputation of stores as well as the purchase decisions of customers.

Therefore, in today’s post, I will provide you with the simplest way to get a review and rating collection in Magento 2.

How to get review, rating collection

To get product review, ratting collection, you need to create a ProductReviews.php file. Follow this path Mageplaza/HelloWorld/Model/ProductReviews.php and here are how you are going to do it.

<?php

namespace Mageplaza\HelloWorld\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();
    }

}

Conclusion

Above is the instruction on how to get product review and rating collection in Magento 2. I hope this post is helpful for you when getting and managing the collection.

Enjoyed the tutorial? Spread it to your friends!