Question

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()
                    ->addAttributeToSelect('*')
                    ->addAttributeToFilter('sku',array('in'=>$skus))
                    ->addAttributeToFilter('visibility',array('gt'=>array(Mage_Catalog_Model_Product_Visibility::VISIBILITY_NOT_VISIBLE)))
                    ->addAttributeToFilter('status',array('eq'=> Mage_Catalog_Model_Product_Status::STATUS_ENABLED))
                    ->addUrlRewrite()
    ;

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

Was it helpful?

Solution

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'));

OTHER TIPS

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');
$collection
    ->addAttributeToSelect('*')
    ->addAttributeToFilter('visibility',array('gt'=>array(Mage_Catalog_Model_Product_Visibility::VISIBILITY_NOT_VISIBLE)))
    ->addAttributeToFilter('status',array('eq'=> Mage_Catalog_Model_Product_Status::STATUS_ENABLED))
    ->addUrlRewrite();

$collection->getSelect()
    ->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.

Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange
scroll top