0

I am filtering product collection like below.

    $productSkuString = 'O, C, D, A, F, S';
        $productSkus = explode(', ', $productSkuString); 
        $collection = $this->collectionFactory->create()
        ->addAttributeToSelect('*')
        ->addAttributeToFilter(
                'sku', array('in' => $productSkus)
        )           
        ->setStoreId(0)
        ->load();
        return $collection;

The above code filtering the product collection with mentioned skus. but not in the same order of the sku.

I need to load the product with same order where the sku is mentioned.

Currently its loading the product in random order.

Can anyone look into it and update me please

  • I found your issue. Please remove space from string. Add like this and then, check it. $productSkuString = 'O,C,D,A,F,S'; $productSkus = explode(',', $productSkuString); – Rohan Hapani Jul 3 at 4:47
  • @RohanHapani, please update me full code, again its made me confused. please update me working code – jafar pinjar Jul 3 at 5:42
  • Check chat room please. – Rohan Hapani Jul 3 at 5:49
1

Use setOrder as below to sort product collection

 $productSkuString = 'O, C, D, A, F, S';
 $collection = $this->collectionFactory->create()
        ->addAttributeToSelect('*')
        ->addAttributeToFilter(
                'sku', array('in' => $productSkus)
        )           
        ->setStoreId(0)
        ->setOrder(new Zend_Db_Expr("FIND_IN_SET('sku', ".$productSkuString.") ASC"))
        ->load();

Reference:

https://stackoverflow.com/a/3265557/10540508

https://magento.stackexchange.com/a/137522/75828

  • tried this code, no change in it, I need to display in this order O, C, D, A, F, S – jafar pinjar Jul 2 at 9:40
  • Ok.. got your point. I edited my code. Try that – Khushbu Jul 2 at 9:44
  • not working again – jafar pinjar Jul 2 at 9:51
  • You need to use Zend_Db_Expr – Khushbu Jul 2 at 9:52
  • Not working after that aslo – jafar pinjar Jul 2 at 10:00
0

Use below code

$productSkus = array("O","C","D","A");
$collection = $this->collectionFactory->create()
        ->addAttributeToSelect('*')
        ->addAttributeToFilter(
                'sku', array('in' => $productSkus)
        )           
        ->setStoreId(0)
        ->setOrder('sku','ASC')
        ->load();

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.