1

I want to get collection in specific order (apart from ASC or DESC order).

Here is my collection:

$productCollection = $block->getProductCollection()
->create()
->addAttributeToSelect('entity_id')
->addFieldToFilter('entity_id',array('in' => array_keys($products_in_orders)))
->addCategoriesFilter(['in' => $category_ids])
->load();

And I want to get collection in exactly array_keys($products_in_orders) this order which is an array of entity_id (e.g. 18,15,16,20)

Here is the reference

1

You can try the following code.

$productIds=array(18,15,16,20);
$productCollection = $block->getProductCollection()
                ->create()
                ->addAttributeToSelect('entity_id')
                ->addFieldToFilter('entity_id',array('in' => array_keys($products_in_orders)))
                ->addCategoriesFilter(['in' => $category_ids]);
$productCollection->getSelect()->order(new \Zend_Db_Expr('FIELD(entity_id,' . implode(',', $productIds).')'));
$productCollection->load();

I didn't test it, but it should work.

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.