Question

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

Thanks

Was it helpful?

Solution

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>
Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange
scroll top