2

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

Thanks

4

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>
5
  • Need to get by category ids -> subcategory ids product collection
    – Shomita
    May 8 '19 at 13:03
  • @Shiwani Check my updated answer. May 9 '19 at 8:57
  • Thanks for the reply. This works for me:)
    – Shomita
    May 10 '19 at 6:55
  • My pleasure @Shiwani :-). May 10 '19 at 7:16
  • For name: $product->getProductName(); & what about product URL & image Apr 27 '20 at 16:40

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.