From e4440201add3548a0ec98b3113e285ed5f6be1dc Mon Sep 17 00:00:00 2001
From: Albertdj <albertusdjauharidjohan@gmail.com>
Date: Wed, 31 Jan 2018 13:16:10 +0700
Subject: [PATCH] Fix sorting by rating and popularity

---
 .../Block/Product/ProductList/Toolbar.php     | 39 ++++++-------------
 1 file changed, 12 insertions(+), 27 deletions(-)

diff --git a/app/code/Magento/Catalog/Block/Product/ProductList/Toolbar.php b/app/code/Magento/Catalog/Block/Product/ProductList/Toolbar.php
index e07385262e9..f1567c59b60 100644
--- a/app/code/Magento/Catalog/Block/Product/ProductList/Toolbar.php
+++ b/app/code/Magento/Catalog/Block/Product/ProductList/Toolbar.php
@@ -198,36 +198,21 @@ class Toolbar extends \Magento\Framework\View\Element\Template
                     $this->getCurrentDirection()
                 )->addAttributeToSort('entity_id', $this->getCurrentDirection());
             }else if($this->getCurrentOrder() == 'rate') {
-                 if ( $this->getCurrentDirection() == 'desc' ) {
 
-                    $this->_collection
-                        ->getSelect()
-                        ->order('e.created_at DESC');
-
-
-                } elseif ( $this->getCurrentDirection() == 'asc' ) {
-
-                    $this->_collection
-                        ->getSelect()
-                        ->order('e.created_at ASC');
-
-                }
+                 $this->_collection->getSelect()->joinLeft(
+                            'rating_option_vote_aggregated',
+                            'e.entity_id = rating_option_vote_aggregated.entity_pk_value',
+                            array('vote_count' => 'SUM(rating_option_vote_aggregated.vote_count)'))
+                    ->group('e.entity_id')
+                    ->order('vote_count desc');
 
             }else if($this->getCurrentOrder() == 'popular') {
-                 if ( $this->getCurrentDirection() == 'desc' ) {
-
-                    $this->_collection
-                        ->getSelect()
-                        ->order('e.created_at DESC');
-
-
-                } elseif ( $this->getCurrentDirection() == 'asc' ) {
-
-                    $this->_collection
-                        ->getSelect()
-                        ->order('e.created_at ASC');
-
-                }
+                $this->_collection->getSelect()->joinLeft( 
+                    'sales_order_item', 
+                    'e.entity_id = sales_order_item.product_id', 
+                    array('qty_ordered'=>'SUM(sales_order_item.qty_ordered)')) 
+                ->group('e.entity_id') 
+                ->order('qty_ordered desc');
 
             }else{
                 $this->_collection->setOrder($this->getCurrentOrder(), $this->getCurrentDirection());
-- 
GitLab