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


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. – Muhammad Anas May 6 '19 at 10:15
  • Hurray! It worked – Muhammad Anas May 6 '19 at 10:24
  • 1
    @Muhammad Hasham, Thanks a lot. It's working – Ravi Soni Jun 25 '20 at 6:36

You have to add addAttributeToSort() to your collection


Code May be Like

$collection->addAttributeToFilter('entity_id', array('in' => $productIdsarray));
  • 2
    Thanks for answering. Actually your code sort the collection based on entity_id. I need to sort the collection based on the product Ids sequence which I have passed to collection. – Muhammad Anas May 6 '19 at 10:15

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.