I am trying to sort a product collection by SKU based on the order that the SKUs appear in the $skus array passed into the addAttributeToFilter method in the collection below:

    $skus = explode(",",$this->getRequest()->getParam('skus'));

    $collection = Mage::getModel('catalog/product')->getCollection()
                    ->addAttributeToFilter('status',array('eq'=> Mage_Catalog_Model_Product_Status::STATUS_ENABLED))

How can I sort this collection so that the products appear in the same order as their skus inside the $skus array?


I have done something similar using the MySQL FIELD() function. Maybe it can also help you here.

After you have added the other filters to your collection, call this:

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

When creating a collection using Mage::getModel('catalog/product')->getCollection() or Mage::getResourceModel('catalog/product_collection') the main collection table is catalog_product_entity. This table contains an sku column which is also indexed so it's most efficient to both filter and sort by this column in the main table. This would give you something like:

$collection = Mage::getResourceModel('catalog/product_collection');
    ->addAttributeToFilter('status',array('eq'=> Mage_Catalog_Model_Product_Status::STATUS_ENABLED))

    ->where('sku IN (?)', $skus)
    ->order('sku DESC');

You don't need to do anything more to order the collection as you are are already filtering by SKU.

I would also recommend you don't just ->addAttributeToSelect('*'), instead add just the attributes you need. Because of the EAV structure of the product tables each attribute added will add complexity to the database query and make the call less efficient.

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

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