1

I am using this Magento 2 add Sort By Best Sellers Option on category products litsing page for Best Seller Products i want to same New Products and Most View Product

2

Try this:

Company\Module\Model\Config

public function getAttributeUsedForSortByArray()
    {
        $options = ['bestseller' => __('Best Seller'), 'newest' => __('Newest'), 'mostviewed' => __('Most Viewed')];
        foreach ($this->getAttributesUsedForSortBy() as $attribute)
        {
            /* @var $attribute \Magento\Eav\Model\Entity\Attribute\AbstractAttribute */
            $options[$attribute->getAttributeCode()] = $attribute->getStoreLabel();
        }

        return $options;
    }

Company\Module\Block\Product\ProductList\Toolbar

public function setCollection($collection)
    {
        // bestseller code

        if($this->getCurrentOrder() == "newest")
        {
            $collection->getSelect()
                ->order('created_at ' . $this->getCurrentDirectionReverse());
        }

        if($this->getCurrentOrder() == "mostviewed")
        {
            $collection->getSelect()->joinLeft(
                'report_event',
                'e.entity_id = report_event.object_id',
                array('view_count' => 'COUNT(report_event.event_id)'))
                ->group('e.entity_id')
                ->order('view_count ' . $this->getCurrentDirectionReverse());
        }

        $this->_collection = $collection;

        $this->_collection->setCurPage($this->getCurrentPage());

        $limit = (int)$this->getLimit();
        if($limit)
        {
            $this->_collection->setPageSize($limit);
        }
        if($this->getCurrentOrder())
        {
            $this->_collection->setOrder($this->getCurrentOrder(), $this->getCurrentDirection());
        }
        return $this;
    }
  • Hi, I am getting error "Exception #1 (PDOException): SQLSTATE[42S22]: Column not found: 1054 Unknown column 'view_count ' in 'order clause'" while use this code. Please help with the solution. – Udit Gupta Jul 5 '18 at 9:16
  • Am too facing this issue. Did you find any solution for this issue? @UditGupta – Prabhu M. Jul 12 at 13:00
0

You can get most viewed product threw SQL you have to just run on phpmyadmin.

SELECT COUNT(report_table_views.event_id) AS `views`, `e`.* FROM `report_event` AS `report_table_views` INNER JOIN `catalog_product_entity` AS `e` ON e.entity_id = report_table_views.object_id AND e.attribute_set_id = '13' WHERE (report_table_views.event_type_id = 1) GROUP BY `e`.`entity_id` HAVING (COUNT(report_table_views.event_id) > 0) ORDER BY `views` DESC

and I am damn sure it will run.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.