0

I am trying to filter Best seller product collection like below.

Seems the setOrder is not working.

  class BestSeller extends \Magento\Framework\View\Element\Template
  {
    protected $_collectionFactory;
    protected $_storeManager;   
    public function __construct(
     \Magento\Backend\Block\Template\Context $context,
     \Magento\Sales\Model\ResourceModel\Report\Bestsellers\CollectionFactory $collectionFactory,
     \Magento\Store\Model\StoreManagerInterface $storeManager, 
     array $data = []
   ) { 
     $this->_collectionFactory = $collectionFactory;
     $this->_storeManager = $storeManager;           
     parent::__construct($context, $data);
  }
  public function getBestSellerData(){      
    $storeId = $this->_storeManager->getStore()->getId();
    $bestSellerProdcutCollection = $this->_collectionFactory->create()
                ->setModel('Magento\Catalog\Model\Product')
                ->setPeriod('day') //you can add period daily,yearly      
                ->setOrder('id', 'desc')
                ->setPageSize(8);  
    return $bestSellerProdcutCollection;

}

This is not filtering the best seller by id with descending order. Can anyone help me on this please.

Thanks

0

You can try this

 public function getBestSellerData(){      
        $storeId = $this->_storeManager->getStore()->getId();
      $objectManager1 = \Magento\Framework\App\ObjectManager::getInstance();
            $productCollection = $objectManager1->create('Magento\Reports\Model\ResourceModel\Report\Collection\Factory');
            $bestSellerProdcutCollection = $productCollection->create('Magento\Sales\Model\ResourceModel\Report\Bestsellers\Collection')->setPeriod('day');
            $bestSellerProdcutCollection->load();
         $bestSellerProdcutCollection->getSelect()->reset(\Magento\Framework\DB\Select::ORDER);
    $bestSellerProdcutCollection->getSelect()->group('sales_bestsellers_aggregated_yearly.product_id')->order('sales_bestsellers_aggregated_yearly.product_id DESC');
        return $bestSellerProdcutCollection;

    }

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.