B-219 Sec-55 Noida, India
+918010221733

How to get a grouped product’s associated products in Magento

This is a question that seems to be asked quite often by new Magento developers.

There is no simple Mage_Catalog_Model_Product::getAssociatedProducts() method, or similar to return all simple products assigned to a grouped product. I outline here how Magento gains access to the collection that we need.

In

/magento/app/design/frontend/base/default/template/catalog/product/view/type/grouped.phtml

you’ll see that they use this:

<?php
    $_associatedProducts = $this->getAssociatedProducts();

Since that .phtml file is of type Mage_Catalog_Block_Product_View_Type_Grouped, we can go to

/magento/app/code/core/Mage/Catalog/Block/Product/View/Type/Grouped.php

and see in Mage_Catalog_Block_Product_View_Type_Grouped::getAssociatedProducts() that they have done this:

<?php
    $this->getProduct()->getTypeInstance(true)->getAssociatedProducts($this->getProduct());

So we can safely assume that $this->getProduct() returns a product object, and replace it with your $product variable like so:

<?php
    $associatedProducts = $product->getTypeInstance(true)->getAssociatedProducts($product);

So a total solution would look something like this:

<?php
    $products = Mage::getModel(‘catalog/product’)
        ->getCollection()
        ->addAttributeToFilter(‘type_id’, array(‘eq’ => ‘grouped’));
    foreach ($products as $product) {
        $associatedProducts = $product->getTypeInstance(true)->getAssociatedProducts($product);
        // Do something with the $associatedProducts collection
    }

(Visited 79 times, 1 visits today)

Leave a reply

You must be logged in to post a comment.