2

I have used below code to filter products by category id.

$_objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$catalog_ids = 4;
$productCollection = $_objectManager- >create('Magento\Catalog\Model\ResourceModel\Product\CollectionFactory');

$collection = $productCollection->create()

->addAttributeToSelect('*')
->addCategoriesFilter(array('in' => $catalog_ids))
->addAttributeToFilter('status', '1')
 ->setOrder('ordered_qty', 'desc')
 ->load();

I am filtering product collection with the category.

Need to filter the collection was most sold items from the category.

How to achieve this. can anyone help me?

1 Answer 1

4
$_objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$catalog_ids = 4;
$productCollection = $_objectManager- >create('Magento\Catalog\Model\ResourceModel\Product\CollectionFactory');

$collection = $productCollection->create()

->addAttributeToSelect('*')
->addCategoriesFilter(array('in' => $catalog_ids))
->addAttributeToFilter('status', '1')
 ->setOrder('ordered_qty', 'desc')
 ->load();

Logic here

$proIds = $collection->getAllIds();

$itemsCollection = $_objectManager- >create('Magento\Sales\Model\ResourceModel\Order\Item\CollectionFactory')->create();
$itemsCollection->addFieldToFilter('product_id', 'in' => $proIds));
$itemCollection ->getSelect()
            ->columns('SUM(qty_ordered) as total_qty')
            ->group('product_id')->setOrder('total_qty');
$bestSeller = $itemsCollection->getColumnValues('product_id');   
$collection->getSelect()->order(new \Zend_Db_Expr('FIELD(entity_id,' . implode(',', $bestSeller).')'));
8
  • Logic code not working for me Sep 4, 2019 at 10:43
  • for this Logic code purpose Order should have been placed then it load colllections and filter it with products ids Sep 4, 2019 at 10:45
  • 1
    @HiteshBalpande yes it gets collection from order first. Sep 4, 2019 at 10:52
  • Is this working? Jan 8, 2020 at 14:18
  • 1
    @KowsiganAtsayam Now you have the product by sale count get the category by-product it is easy. Jan 8, 2020 at 14:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.