I need to get the collection using custom product Ids but it should sort the collection based on the sequence product Ids given

Here is what I am doing now, but it is not sorting in sequence

$collection->addAttributeToFilter('entity_id', array('in' => $productIdsarray));

Any help would be appreciated

1 Answer 1


You just need to add order along with your addAttributeToFilter

$collection->addAttributeToFilter('entity_id', array('in' => $productIdsarray ));
$collection->getSelect()->order(new \Zend_Db_Expr("FIELD(e.entity_id, ".implode(",",$productIdsarray).")"));
  • Thanks Will try this and get back to you. May 6, 2019 at 10:15
  • Hurray! It worked May 6, 2019 at 10:24
  • 1
    @Muhammad Hasham, Thanks a lot. It's working
    – Ravi Soni
    Jun 25, 2020 at 6:36
  • 1
    It's not working in Magento 2.4.1 Version Jul 6, 2021 at 11:59

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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