Get product stock quantity in magento
It's working for me.
$products = Mage::getModel('catalog/product')->getCollection();
foreach ($products as $_product) {
$stock = Mage::getModel('cataloginventory/stock_item')->loadByProduct($_product);
echo $stock->getQty();
echo $stock->getMinQty();
echo $stock->getMinSaleQty();
}
You will need to join the table to get qty.
See below code:
$products = Mage::getModel('catalog/product')
->getCollection()
//->addAttributeToSelect('*')
->addAttributeToSelect(array('name', 'thumbnail', 'weight' ,'price','description'))
->joinField(
'qty',
'cataloginventory/stock_item',
'qty',
'product_id=entity_id',
'{{table}}.stock_id=1',
'left'
);
foreach ($products as $product) {
$p['products'][] = array(
'id' => $product->getId(),
'sku' => $product->getSku(),
'name' => $product->getName(),
'description' => $product->getDescription(),
'weight' => $product->getWeight(),
'created at' => $product->getCreatedAt(),
'pirce' => Mage::helper('core')->currency($product->getPrice(), true, false), //." ".$currencyCode,
//get qty
'qty' => $product->getQty(),
);
}
How to get created attribute value here for eg i have created a attribute named size how to fetch that value
UPDATE (Although you should ask in another qst, but I will answer here for you.)
To get custom attribute you will need to add attribute in ->addAttributeToSelect
section.
Still doesn't work?
You might need to load a product model as sometimes I've experienced that not all custom attributes are attached when you pull it out of a collection (intended for performance reasons I guess). Something like:
$_product = Mage::getModel('catalog/product')->load($product->getId());
$size = $_product->getSize();
Adding stock information to product collections can be done with a single line:
/* Mage_Catalog_Model_Resource_Product_Collection */
$products->setFlag('require_stock_items', true);
This flag is used in catalog_product_collection_load_after
observer:
/**
* Add information about producs stock status to collection
* Used in for product collection after load
*
* @param Varien_Event_Observer $observer
* @return Mage_CatalogInventory_Model_Observer
*/
public function addStockStatusToCollection($observer)
{
$productCollection = $observer->getEvent()->getCollection();
if ($productCollection->hasFlag('require_stock_items')) {
Mage::getModel('cataloginventory/stock')->addItemsToProducts($productCollection);
} else {
Mage::getModel('cataloginventory/stock_status')->addStockStatusToProducts($productCollection);
}
return $this;
}
If this flag is not set $product->getStockItem()->getData()
has only is_in_stock
set. With flag you can get qty, backorders, ... for every product in collection
foreach ($products as $product) {
echo $product->getStockItem()->getQty();
}