Magento – Sort product collection after load

product-listsortsorting

I have a module that shows some product that I want to sort by ID.

I'm trying the following code with no success

<?php
    $_productCollection=$this->getLoadedProductCollection();
    $_helper = $this->helper('catalog/output');
$_productCollection->addAttributeToSort('entity_id', 'desc');
?>

Any ideas?

Best Answer

Collections inherit from the class

Varien_Data_Collection_Db

There's a method named addOrder on that class.

public function addOrder($field, $direction = self::SORT_ORDER_DESC)
{
    return $this->_setOrder($field, $direction);
}

So, you'd think something like this should work for basic ordering

Mage::getModel('catalog/product')
->getCollection()
->addAttributeToSelect('*')
->addOrder('entity_id');

However, it doesn't. Because of the complex joining involved in EAV Collections, there's a special method used to add an attribute to the order clause

Mage_Catalog_Model_Resource_Eav_Mysql4_Product_Collection::addAttributeToSort

However again, this can only be used to add simple attributes. To create an arbitrary sort, you'll need to manipulate the Zend_Select object directly. I'm not a big fan of this, and I'm not a big fan of using custom mysql functions to achieve things, but it appears it's the only way to do this

I tested the following code on a stock install and got the desired results. You should be able to use it to get what you want.

        $products = Mage::getModel('catalog/product')->getCollection()
        ->addAttributeToSelect('*');

        //shakes fist at PDO's array parameter
        $products->getSelect()->order("entity_id DESC");
        foreach($products as $product)
        {
            var_dump($product->getEntityId());
            var_dump($product->getSku());
        }

Hope this helps

Related Topic