How to sort Products by quantity and price in Ascending or Descending order programatically?
I was facing issue to sort products by quantity and price in descending order i.e. products which is having maximum quantity in stock and with highest price should be listed first.
Example:
Products Quantity Price
A 10 1500
B 9 1400
C 8 1000
D 6 500
I have achieved this by writing this code in /app/code/core/Mage/Catalog/Model/Resource/Product/Collection.php
Just write this code:
$select = $this->getSelect();
$select->joinLeft(
array('stock_qty' => $this->getTable('cataloginventory/stock_status')),
'e.entity_id = stock_qty.product_id AND stock_qty.website_id='.Mage::app()->getWebsite()->getId(),
array(
'salable' => 'stock_qty.stock_status',
'qty' => 'stock_qty.qty'
)
);
//get the reversed sorting
//if by position ascending, then you need to sort by qty descending and the other way around
$reverseDir = ($dir == 'ASC') ? 'DESC' : 'ASC';
//this is optional - it shows the in stock products above the out of stock ones independent if sorting by position ascending or descending
$this->getSelect()->order('salable DESC');
//sort by qty
$this->getSelect()->order('qty '.$reverseDir);
$this->getSelect()->order('price DESC');
return $this;
All done now, now refresh the magento cache and you will find that products which is having maximum quantity will be listed first along with the highest price
0 Comment(s)