How to Get Review, Rating Collection in Magento 2?

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.


Better Product Reviews

Better Product Reviews for Magento 2

Motivate shoppers to make faster decisions by displaying top-rated products from previous customers

Check it out!


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.

Image Description
With over a decade of experience crafting innovative tech solutions for ecommerce businesses built on Magento, Jacker is the mastermind behind our secure and well-functioned extensions. With his expertise in building user-friendly interfaces and robust back-end systems, Mageplaza was able to deliver exceptional Magento solutions and services for over 122K+ customers around the world.
x