Magento 2.2 – Sort Reviews by Rating

collection;magento2.2reviewsorting

I want to add sorting in Review Listing. What is the logic to add Sort by ratings?

enter image description here

I have override method getReviewsCollection() of Magento/Review/Block/Product/View.php So I have $this->_reviewsCollection on my hand.

Anyone has Idea how to apply sort on base of rating?

Best Answer

I found the Solution as below:

$countColumn = new \Zend_Db_Expr("COUNT(*)");
$percentColumn = new \Zend_Db_Expr("SUM(percent)/".$countColumn );

$this->_reviewsCollection->getSelect()->joinLeft(
   ['rating_vote'=>$this->_reviewsCollection->getTable('rating_option_vote')],
   'rating_vote.review_id=main_table.review_id',
   ['sum' => 'SUM(percent)', 'count' => $countColumn, 'average' => $percentColumn]);

$this->_reviewsCollection->getSelect()->group('rating_vote.review_id');

$this->_reviewsCollection->getSelect()->order('average desc');
Related Topic