Magento Product Stock – How to Get Product Stock Quantity

magento-1.9productsstock

I need to get product stock quantity for the item, how to get that

$products = Mage::getModel('catalog/product')->getCollection();
$products->addAttributeToSelect(array('name', 'thumbnail', 'weight' ,'price','description'));

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,
    );
}

Best Answer

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();  
Related Topic