I have a custom page that I have put together that basically shows products that are on sale. I was asked if I could sort the products coming out of the collection by the highest percentage of discount.
So I am wondering if it is possible to set the order of products based on the mathematical result of diving two other attributes together.
I think I figured it out. Alan Storm previously helped me with a similar problem I was having sorting products in an arbitrary way.
Magento get a product collection in an arbitrary order
Using the same idea I came up with the following code to make this work:
$products = Mage::getModel('catalog/category')->load($category_id)
->getProductCollection()
->addAttributeToSelect('name')
->addAttributeToSelect('price')
->addAttributeToSelect('small_image')
->addAttributeToFilter('status', 1)
->addAttributeToFilter('visibility', 4)
->addAttributeToFilter('special_price', array('neq' => ""))
->addAttributeToFilter('discontinued', array('neq' => 1))
->setPageSize($results_per_page)
->setCurPage($current_page)
;
$products->getSelect()->order('(`e`.special_price / `e`.`price`)', 'DESC');
Credit should go to Alan Storm on this one.