How to filter products by rating in Magento 2?
Question
I want to get all products by rating filter. here my code
$getProducts = $objectManager->create('Magento\Catalog\Model\ResourceModel\Product\Collection');
$getProducts->addAttributeToSelect('*');
$getProducts->addAttributeToFilter('visibility', 4);
So, how can I add here filter for rating so I need not to first get all product and then check all product with that rating issue.
thanks
Solution
You can try the below code for filter product collection by rating percent:
$collection = $_objectManager->create('Magento\Catalog\Model\ResourceModel\Product\Collection');
$collection->addAttributeToSelect('*');
$collection->getSelect()->joinLeft(array('rova'=> 'rating_option_vote_aggregated'),'e.entity_id =rova.entity_pk_value', array("percent" => 'percent'))->group('e.entity_id');
$collection->getSelect()->where("rova.percent = 80");
foreach($collection as $product){
//YOUR CODE
}
100 Percent = 5 Star Rating
90 Percent = 4.5 Star Rating
80 Percent = 4 Star Rating
and so on...
Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange