Magento 2 - Get Collection using custom product Ids and also sort them as the same order as product Ids passed
-
28-02-2021 - |
Question
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
La solution
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).")"));
Autres conseils
You have to add addAttributeToSort() to your collection
addAttributeToSort('entity_id')
Code May be Like
$collection->addAttributeToFilter('entity_id', array('in' => $productIdsarray));
$collection->addAttributeToSort('entity_id');
Licencié sous: CC-BY-SA avec attribution
Non affilié à magento.stackexchange