3

On the cart page I need to be able to obtain the parent SKU using a child SKU.

I've tried several code snipped from both the Magento forums and similar questions here on StackOverflow without success.

I'm able to determine if a product is just a simple product without a parent by using getTypeId() but after that everything I try fails to result in getting at the parent SKU.

Magento Version: 1.4.2.0

Chris Cummings
  • 2,007
  • 5
  • 25
  • 39

1 Answers1

13

Take a look at the Mage_Catalog_Model_Product_Type_Configurable and Mage_Bundle_Model_Product_Type classes. They have useful methods for getting parent and child products. You want getParentIdsByChild():

For configurable products:

$parent_ids = Mage::getModel('catalog/product_type_configurable')->getParentIdsByChild($childId);

For bundle products:

$parent_ids = Mage::getModel('bundle/product_type')->getParentIdsByChild($childId);

These only work with ids. You'll need to convert the child SKU to an id and then the parent id back to a SKU. A simple way to get the id from the SKU is:

Mage::getModel('catalog/product')->getIdBySku($sku);

Also, you can have multiple parent ids, so you'll have to be aware of that. Here's an example:

$child_id = Mage::getModel('catalog/product')->getIdBySku($child_sku);
$parent_ids = Mage::getModel('catalog/product_type_configurable')->getParentIdsByChild($child_id);
$parent_collection = Mage::getResourceModel('catalog/product_collection')
    ->addFieldToFilter('entity_id', array('in'=>$parent_ids))
    ->addAttributeToSelect('sku');
$parent_skus = $parent_collection->getColumnValues('sku');
Joe
  • 1,330
  • 13
  • 15
  • This was exactly what I needed. Thanks! Sorry for the delay in marking your response as the answer. I only just now got the opportunity to try it. – Chris Cummings Jul 17 '12 at 13:12
  • 1
    There exists also method Mage::getModel('catalog/product')->getResource()->getProductsSku(array(1,2,3) that returns the products skus by products ids. – Jiří Chmiel Mar 27 '13 at 12:31
  • I get `Data load getParentIdsByChild() method detected in loop` warning while checking the codebase using `phpcs` when use the method in a loop which iterates over all the products. How can we fix that? – Amit Patel Dec 12 '17 at 10:44
  • @AmitPatel Does this answer help? https://magento.stackexchange.com/a/148163/9276 – Joe Dec 15 '17 at 16:15
  • How to get this on magento 2? – huykon225 May 31 '21 at 07:20