1

I am get bestseller product using below code but it will not display best seller products of latest month, It will display bestseller product from starting.

Can anyone tell me how can I filter best seller product.

Thanks In Advance.

<?php
    $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
    $productCollection = $objectManager->create('Magento\Reports\Model\ResourceModel\Report\Collection\Factory'); 
    $collection = $productCollection->create('Magento\Sales\Model\ResourceModel\Report\Bestsellers\Collection'); 

     $collection->setPeriod('month');      

    foreach ($collection as $item) {
        print_r($item->getData());
    }

In short I want to implement below query logic.

SELECT * FROM sales_bestsellers_aggregated_monthly ORDER BY sales_bestsellers_aggregated_monthly.id DESC

1

Use this below code in your block :

namespace RH\HelloWorld\Block;

class BestSeller extends \Magento\Framework\View\Element\Template
{

  protected $_collectionFactory;
  public function __construct(
      \Magento\Backend\Block\Template\Context $context,
      \Magento\Sales\Model\ResourceModel\Report\Bestsellers\CollectionFactory $collectionFactory,
      array $data = []
  ) {
      $this->_collectionFactory = $collectionFactory;
      parent::__construct($context, $data);
  }

  public function getBestSellerData(){
    $bestSellerProColl = $this->_collectionFactory->create()->setModel('Magento\Catalog\Model\Product')->setPeriod('month');
    return $bestSellerProColl;
  }
}

Use in your phtml like :

$bestSellerData = $block->getBestSellerData();

foreach ($bestSellerData as $key => $value) {
  echo "Product Name : ".$value->getProductName()."<br/>";
}

Note : Make sure data available in database.

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.