Magento 2 – Custom Sort Order for Product Collection

magento2productproduct-collection

For example, I want collection list in order "sku2,sku3,sku1", it is not simple DESC or ASC order. How to achieve it?

Example codes is below:

$skus = 'sku2,sku3,sku1';
$collection->addAttributeToSelect('*')
    ->addAttributeToFilter(
        'sku', array('in' => $skus)
    );

Magento 1.x has a way here How to specify custom sort order for product collection?, but it doesn't work on Magento 2:

$collection->getSelect()->order(new Zend_Db_Expr("FIELD(e.sku, $skus)"));

Fatal error: Uncaught Error: Class '…/Zend_Db_Expr' not found in …

Best Answer

You can do in magento 2 as below way, use \Zend_Db_Expr

$collection->getSelect()->order(new \Zend_Db_Expr('FIELD(e.entity_id, ' . implode(',', $skus).')'));