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 :开发者_Go百科)
Thanks!
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);
try this as well...
$stockCollection = Mage::getModel('cataloginventory/stock_item')->getCollection()->addFieldToFilter('qty', array('gteq' => 1))->addFieldToFilter('type_id', 'simple');
addFieldFilter ('qty',array('gteq' =>1))
get all products collection that have a stock of 1 or greater, you can put any number here according to your needs
addFieldToFilter('type_id', 'simple')
filter by simple products
I stumbled upon the problem that isSaleable() always returns false on my products, the problem was that I was getting the collection but didn't add the attribute price to the collection. In the isSaleable() function there is a check to make sure the price isn't 0, it needs the price attribute to check that so:
Changing:
$collection = Mage::getModel('catalog/product')->getCollection();
$collection->addAttributeToSelect('name')
->addAttributeToSelect('image')
->addAttributeToSelect('url_path')
->addAttributeToSelect('status')
->addUrlRewrite();
To:
$collection = Mage::getModel('catalog/product')->getCollection();
$collection->addAttributeToSelect('name')
->addAttributeToSelect('image')
->addAttributeToSelect('price')
->addAttributeToSelect('url_path')
->addAttributeToSelect('status')
->addUrlRewrite();
Did the trick :)
精彩评论