1

I want to sort product collection by category ids. I used this below code. What i need to add in this code ?

/**
 * @var \Magento\Catalog\Model\ResourceModel\Product\CollectionFactory
 */
protected $productCollectionFactory;

public function __construct(
    .....
    \Magento\Catalog\Model\ResourceModel\Product\CollectionFactory $productCollectionFactory
    .....
) {
    .....
    $this->productCollectionFactory = $productCollectionFactory;
    .....
}


publi function yourfunction()
{
    $catalog_ids = ['14', '61', '62', '63'];
    $productCollection = $this->productCollectionFactory->create();
    $productCollection->addCategoryIds()->addCategoriesFilter(['in' => $catalog_ids])->addAttributeToSelect('*');
    $productCollection->addAttributeToFilter('size_mm', ['eq' => 2650]);
    $productCollection->setOrder('size_mm', 'DESC');
    $productCollection->setOrder('entity_id', 'ASC');
    return $productCollection;
}
2

You have one option as following:

        public function yourfunction()
        {
            $catalog_ids = ['14', '61', '62', '63'];
            $sortedCategoryProducts = array();
             foreach($catalog_ids as $catalog_id){
                $productCollection = $this->productCollectionFactory->create();
                $productCollection->addCategoriesFilter(['in' => 
                $catalog_id])->addAttributeToSelect('*'); // instead * add only those attributes which you actually need in this change you don't bother that category loads 4 times
                $productCollection->addAttributeToFilter('size_mm', ['eq' => 2650]);
                $productCollection->setOrder('size_mm', 'DESC');
                $productCollection->setOrder('entity_id', 'ASC');

           foreach ($productCollection as $product) {
                // here you can also place check to skipp redundant product
                $sortedCategoryProducts[] = $product->getData();
            }
        }

            return $sortedCategoryProducts;
        }
  • Please verify your code. It returns errors. – Emipro Technologies Pvt. Ltd. Apr 9 at 7:24
  • 1
    Your answer is correct. Please update your answer. Your if condition return error so. So, after correction i will accept it. – Emipro Technologies Pvt. Ltd. Apr 9 at 7:28
  • @EmiproTechnologiesPvt.Ltd. Actually the condition you removed is required to avoid repetitions becaus one product can be in different categories, you just need to verify at which key in $sortedCategoryProducts 'entity_id' present. add it in condition. – Hassan Ali Shahzad Apr 9 at 9:42
  • Ohh...!! Sorry. Can you please again add that code? – Emipro Technologies Pvt. Ltd. Apr 9 at 10:16

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.