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).')'));

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

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