Magento - how do I get associated products of product Group?

后端 未结 3 767
灰色年华
灰色年华 2021-01-31 11:55

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::getM         


        
相关标签:
3条回答
  • 2021-01-31 12:41

    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
        }
    
    0 讨论(0)
  • 2021-01-31 12:49

    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);
    }
    
    0 讨论(0)
  • 2021-01-31 12:51

    To get product collection by type:

    $product = Mage::getModel('catalog/product')
       ->getCollection()
       ->addAttributeToFilter('type_id', array('eq' => 'grouped'))
       ->load();
    
    $parentProductId = array();
    
    foreach($product as $simpleProducts) {
      $simpleProducts->loadParentProductIds();
      array_push($parentProductId,$simpleProducts->getParentProductIds();
    }
    
    0 讨论(0)
提交回复
热议问题