Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get associated products of product Group?

Tags:

magento

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?
    }
}
like image 810
Owen Avatar asked Dec 20 '11 17:12

Owen


2 Answers

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
    }
like image 185
Magento Guy Avatar answered Oct 22 '22 06:10

Magento Guy


Or if you want just to get ids of associated products, you can use the following method (it is much faster):

public function getAssociatedProductIds($groupedProductId)
{
    $coreResource = Mage::getSingleton('core/resource');
    $conn = $coreResource->getConnection('core_read');
    $select = $conn->select()
        ->from($coreResource->getTableName('catalog/product_relation'), array('child_id'))
        ->where('parent_id = ?', $groupedProductId);

    return $conn->fetchCol($select);
}
like image 6
Roman Snitko Avatar answered Oct 22 '22 08:10

Roman Snitko