1

I need to get Bestseller products collection by category ids(subcategories)

Thanks

1

Step 1: Create a block file

<?php
namespace QaisarSatti\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($category_ids)
{
    $bestSellerProdcutCollection = $this->_collectionFactory->create()
        ->setModel('Magento\Catalog\Model\Product')
        ->setPeriod('month')
        ->join(['secondTable' => 'catalog_category_product'], 'sales_bestsellers_aggregated_monthly.product_id = secondTable.product_id', ['category_id' => 'secondTable.category_id'])
        ->addFieldToFilter('category_id', $category_ids);

    return $bestSellerProdcutCollection;
}
}

Step 2: Show Output

Getting collection in phtml file from block.

<?php $category_ids = [1,2,3,4]; ?>
<?php $bestSeller = $block->getBestSellerData($category_ids); ?>
<h1>Best Seller Collection.....</h1>
<ul>
    <?php foreach ($bestSeller as $product): ?>
        <li><?php echo $product->getProductName(); ?>--<?php echo $product->getQtyOrdered(); ?></li>
    <?php endforeach; ?>
</ul>
  • Need to get by category ids -> subcategory ids product collection – Shiwani May 8 at 13:03
  • @Shiwani Check my updated answer. – Pratik Mehta May 9 at 8:57
  • Thanks for the reply. This works for me:) – Shiwani May 10 at 6:55
  • My pleasure @Shiwani :-). – Pratik Mehta May 10 at 7:16

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.