How to get parent product id in magento?

veilig picture veilig · Aug 10, 2011 · Viewed 46.1k times · Source

I know that in Magento 1.4.2.0 one gets parent id's like so

list( $parentId ) = Mage::getModel('catalog/product_type_configurable')
                            ->getParentIdsByChild( $product->getId() );

My question is: if I don't know what the parent is, how do I know to use the 'catalog/product_type_configurable' vs 'catalog/product_type_grouped' model to get the id?

Answer

Kus picture Kus · Aug 7, 2012

You can just call both and offer a fall-back as it should be one or the other:

if($product->getTypeId() == "simple"){
    $parentIds = Mage::getModel('catalog/product_type_grouped')->getParentIdsByChild($product->getId());
    if(!$parentIds)
        $parentIds = Mage::getModel('catalog/product_type_configurable')->getParentIdsByChild($product->getId());
    if(isset($parentIds[0])){
        $parent = Mage::getModel('catalog/product')->load($parentIds[0]);
        // do stuff here
    }
}