Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

filtering product collection on "is_salable"

I would like to filter a product collection to show only items that are in stock. I thought this would be easy given that there's an attribute called 'is_salable' that is 1 (true) if it's in stock, 0 (false) if not. But no matter what I do, it doesn't work. Further, it seems to halt the execution of the query before it finishes.

Here's some sample code:

$this->_productCollection = Mage::getModel('catalog/product')->getCollection();
$this->_productCollection->addAttributeToSelect('*');
$this->_productCollection->addAttributeToFilter('my_attribute', true);
//So far, so good...filtering on 'my_attribute' works!
Mage::Log("select: " . $this->_productCollection->getSelect());
//Successfully outputs the SQL query
$this->_productCollection->addFieldToFilter('is_salable', '1');
Mage::Log("select: " . $this->_productCollection->getSelect());
//does NOT output any query...it's like it died trying

So what am I doing wrong? I've tried 'addFieldToFilter', 'addAttributeToFilter', and miscellaneous other queries, such as: addFieldToFilter('is_salable', array('eq' => true)), etc...

Anyone know how to do this? If 'is_salable' is not the answer, all I need to do is filter out products that are not in stock...so whatever works to do that would be fine :)

Thanks!

like image 957
Mageician Avatar asked Mar 14 '11 17:03

Mageician


1 Answers

There is no is_salable attribute in the product so it will rise an exception. If you want to display only products that are in stock, use this stock model addInStockFilterToCollection method:

Mage::getSingleton('cataloginventory/stock')->addInStockFilterToCollection($this->_productCollection);
like image 144
Ivan Chepurnyi Avatar answered Oct 04 '22 06:10

Ivan Chepurnyi