0

How to get the best selling products in a category and sort them from best selling to least selling?

I try get best selling collection like:

use Magento\Store\Model\StoreManagerInterface;
use Magento\Sales\Model\ResourceModel\Report\Bestsellers\CollectionFactory;
use Magento\Catalog\Model\ResourceModel\Product\CollectionFactory;

public function getMyBestSellers() {
        $storeId = $this->storeManager->getStore()->getId();
        $bestSellers = $this->bestsellersCollectionFactory->create()
            ->addStoreFilter($storeId)
            ->setPeriod('daily')
            ->setDateRange(null, null)
            ->setOrder('qty_ordered', 'DESC');

        $productIds = [];
        foreach ($bestSellers as $bestSeller) {
            $productIds[] = $bestSeller->getProductId();
        }

        return $this->productCollectionFactory->create()
            ->addCategoriesFilter(['in' => $categoryId])
            ->addIdFilter($productIds)
            ->addStoreFilter($storeId)
            ->addAttributeToSelect('*');
}

But as a result, my products are not sorted by the number of sales made. Please help solve this problem.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.