0

I am quite a new to magento, but trying hard to learn it and know all it models and collections. I had a requirement to get the size of all the simple products and its quantity. We do have the size attribute set and many product are of type configurable and we are displaying that on the list page as well.

Configurable product do have the quantity and size as it is associates all the simple products.

Now i am really curious to know the stock in this format.

stock ={
"size" => "quantity"
 }

where size is the attribute and it can be x,xl,xs,xxl,xxxl and so on. and quantity is the quantity which is in stock for that particular size.

What i have tried uptill now is to get the name,id,sku,product url, images url and category id as well.

$collection = Mage::getModel('catalog/product')->getCollection()
->addAttributeToSelect('*');
// set the offset (useful for pagination)

// we iterate through the list of products to get attribute values
foreach ($collection as $product) {
  echo $product->getName(); //get name of the product
  echo "<br/>";
  echo (float) $product->getPrice(); //get price as cast to float
   echo "<br/>";
  echo $product->getDescription(); //get description
   echo "<br/>";

   echo $product->getSku(); //get sku
   echo "<br/>";
echo (int)Mage::getModel('cataloginventory/stock_item')
                ->loadByProduct($product)->getQty(); //get the qty of the product
   echo "<br/>";


  // getCategoryIds(); returns an array of category IDs associated with the product
  foreach ($product->getCategoryIds() as $category_id) {
      $category = Mage::getModel('catalog/category')->load($category_id);
       echo "<br/>";
 echo $category->getName(); //get name of the category && sub-category
       echo "<br/>";
  }
  echo '<br/>';

  //gets the image url of the product


             //var_dump($product->getMediaGalleryImages());
echo "<br/>";
  echo $product->getProductUrl();  //gets the product url
  echo '<br />';
echo $product->getSize();  
  echo '<br />';
$product1 = Mage::getModel('catalog/product')->load($product->getID())->getMediaGalleryImages();//product

$items = array();

foreach($product1 as $gimage) {
    $items[] = $gimage['url'];
}
$t = implode(',', $items);

echo $t;

echo "</br>";
}

Now, how will i be able to fetch the quantity and size in the format mentioned above foreach product using the above collection ??

1

The following snippet is an example to retrieve what you need.

$products = Mage::getModel('catalog/product')->getCollection()
    ->addAttributeToSelect('sku')
    ->addAttributeToSelect('name')
    ->addAttributeToSelect('type_id');

if (Mage::helper('catalog')->isModuleEnabled('Mage_CatalogInventory')) {
    $products->joinField('qty',
        'cataloginventory/stock_item',
        'qty',
        'product_id=entity_id',
        '{{table}}.stock_id=1',
        'left');
}

foreach ($products as $product) {
    printf(
        "Type: %s - SKU: %s - Name: %s - Qty: %d" . PHP_EOL,
        $product->getTypeId(),
        $product->getSku(),
        $product->getName(),
        $product->getQty()
    );
}

Refer to Mage_Adminhtml_Block_Catalog_Product_Grid to see some examples about how to properly retrieve product collections.

Hope it helps.

EDIT

This one should give the desired output:

/** @var Mage_Catalog_Model_Product $confProduct */
// Replace this with your configurable product instance
$confProduct = Mage::getModel('catalog/product')->load(877); // sample ID

$productIds = $confProduct
    ->getTypeInstance(true)
    ->getUsedProductIds($confProduct);

$confAttributeCodes = array_map(
    function($attribute) {
        return $attribute['attribute_code'];
    },
    $confProduct->getTypeInstance(true)->getConfigurableAttributesAsArray($confProduct)
);

$products = Mage::getModel('catalog/product')->getCollection()
    ->addAttributeToSelect('sku')
    ->addAttributeToSelect('name')
    ->addAttributeToSelect('type_id')
    ->addAttributeToSelect($confAttributeCodes)
    ->addFieldToFilter('entity_id', array('in' => $productIds));

if (Mage::helper('catalog')->isModuleEnabled('Mage_CatalogInventory')) {
    $products->joinField('qty',
        'cataloginventory/stock_item',
        'qty',
        'product_id=entity_id',
        '{{table}}.stock_id=1',
        'left');
}

$result = array();
foreach ($products as $product) {
    $label = array_reduce(
        $confAttributeCodes,
        function ($carry, $item) use ($product) {
            return $carry . $product->getAttributeText($item) . ' ';
        },
        ''
    );
    $result[trim($label)] = $product->getQty();
}
echo json_encode($result);

To get the results for each configurable product, remove the line that begins with $confProduct = ... and wrap all the code block within the following foreach

$confProducts = Mage::getModel('catalog/product')->getCollection()
    ->addFieldToFilter('type_id', Mage_Catalog_Model_Product_Type::TYPE_CONFIGURABLE);
foreach ($confProducts as $confProduct) { 
    // put the above code here, without $confProduct assignment
}

Note: I suggest you to add necessary filters to the configurable products collection (visibility, status etc.)

  • Hi @Alessandro, I need the qty according to the size attribute, suppose if there is a configurable product and it has simple products with different sizes, is it possible to get this type of array stock: {"s" => 1, "xl" => 2}, where s and xl are the sizes and 1, and 2 are the stock related to it . Can we get in this way ? – Jay Desai Feb 15 '16 at 9:16
  • Ji @Coold, please refer to the above answer, I added a code snippet that should give you the desired result. – Alessandro Ronchi Feb 16 '16 at 9:08
  • Hi @Coold, I also considered that there can be more than a configurable attribute, this complicated the code a bit but made it more general. Cheers. – Alessandro Ronchi Feb 16 '16 at 9:15
  • Hey @Alessandro, Love you for this one, thank you so much..:) – Jay Desai Feb 16 '16 at 9:28
  • Hi @Alessandro, how will be able to do foreach of the products, with my code above, need to load this result for every product. – Jay Desai Feb 17 '16 at 11:10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.