Magento (CE 1.3) - Filter ProductCollection Where Stock Quantity Is 0
Introduction
In Magento CE 1.3, filtering products based on stock quantity can be a bit tricky due to the way the qty attribute is managed. In this post, we’ll walk through how to correctly filter out of stock items from your product collection.
Understanding the Issue with Quantity Filtering
The main challenge lies in using the addAttributeToFilter('qty', array('gt' => 0)) method. This returns an error stating that ‘qty’ is not an attribute. The issue stems from how Magento 1.x handles the stock quantity.
The Correct Approach: Using Stock Item Collection
Instead of trying to filter directly on the qty attribute, we need to use the stock_item collection associated with each product. Here’s a step-by-step guide:
Step 1: Load Your Product Collection
First, ensure you have loaded your product collection and selected all necessary attributes:
$this->productCollection = $this->productCollection
->addAttributeToSelect('*')
->setStoreId($storeId)
->addStoreFilter($storeId);
Step 2: Join the Stock Item Collection
Next, we need to join our product collection with the stock_item collection. We’ll use the joinField method:
$this->productCollection = $this->productCollection
->joinField('stock_item', 'cataloginventory/stock_item', 'item_id', 'product_id=entity_id',
null, 'left');
This joins the stock_item table to our product collection on the product_id field.
Step 3: Filter By Stock Quantity
Now we can filter by stock quantity. We’ll use the addFieldToFilter method:
$this->productCollection = $this->productCollection
->addFieldToFilter('stock_item.qty', array('gt' => 0));
We’re filtering on the stock_item.qty field, which represents the stock quantity of each item.
Complete Example
Combining all the steps above, your full product collection setup should look like this:
$this->productCollection = $this->productCollection
->addAttributeToSelect('*')
->setStoreId($storeId)
->addStoreFilter($storeId)
->joinField('stock_item', 'cataloginventory/stock_item', 'item_id', 'product_id=entity_id',
null, 'left')
->addFieldToFilter('status', array('neq' => Mage_Catalog_Model_Product_Status::STATUS_DISABLED))
->addFieldToFilter('stock_item.qty', array('gt' => 0))
->setPageSize($this->getToolbarBlock()->getLimit());
This will give you a collection of enabled products with stock quantities greater than zero.
Conclusion
When working with Magento CE 1.3, it’s crucial to understand the relationship between product and stock_item tables when dealing with stock quantity filtering. By joining these tables correctly and using the appropriate filter methods, you can efficiently retrieve only the in-stock products for your store view.
Remember, as a developer, understanding the underlying data structure is key to writing efficient and accurate code. Always refer to the official Magento documentation or use tools like Laravel Company’s Magento 1.x tutorials for in-depth guidance.
Happy coding!