0

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?

3
$_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).')'));
  • Logic code not working for me – Hitesh Balpande Sep 4 at 10:43
  • for this Logic code purpose Order should have been placed then it load colllections and filter it with products ids – Hitesh Balpande Sep 4 at 10:45
  • 1
    @HiteshBalpande yes it gets collection from order first. – Qaisar Satti Sep 4 at 10:52

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.