Search code examples
magento

How do I get associated products of product Group?


I am looping through products results, and if the product is a grouped product, I want to get all products in that group. I'm doing this:

$products = Mage::getModel('catalog/product')
                    ->getCollection()
                    ->addAttributeToSelect('*');
foreach ($products as $product) {
    if ($product->getTypeId() == 'grouped'){
        // how do I now get associated products of $product?
    }
}

Solution

  • 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 that Mage_Catalog_Block_Product_View_Type_Grouped::getAssociatedProducts() does this:

    <?php
        $this->getProduct()->getTypeInstance()->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
        if ($product->getTypeId() == 'grouped'){
            // how do I now get associated products of $product?
            $associatedProducts = $product->getTypeInstance()->getAssociatedProducts($product);
        }
    

    If I was to optimise your code completely, I'd write it like this:

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