12

How to get a child's parent product id in Magento 2 for the configurable products?

I want to get the parent product id of child product in Magento based on child product id.

2 Answers 2

31

For getting the parent product id in your phtml file, you can call code directly by:

    $productId = 52; //this is child product id
    $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
    $product = $objectManager->create('Magento\ConfigurableProduct\Model\ResourceModel\Product\Type\Configurable')->getParentIdsByChild($productId);
     if(isset($product[0])){
         //this is parent product id..
         echo $product[0];
    }
4
  • its working fine in view file.
    – user32787
    Dec 4, 2015 at 6:27
  • 8
    You shouldn't use the object manager directory. Inject a factory using the ->create method
    – CarComp
    Jan 24, 2017 at 19:12
  • @Rakesh after get configurable product id how can i get only all detail about particular configurable product? Can i load product model via parent product id? Apr 3, 2019 at 6:13
  • Not working anymore in Magento 2.4! Returns empty array []
    – Max
    Nov 8, 2021 at 22:52
14

You can call it's in block file, Magento specific way by,

protected $_catalogProductTypeConfigurable;

public function __construct(
    \Magento\Catalog\Block\Product\Context $context,
    //for getting parent id of simple
    \Magento\ConfigurableProduct\Model\ResourceModel\Product\Type\Configurable $catalogProductTypeConfigurable,
    array $data = []
) {
    //for getting parent id of simple
    $this->_catalogProductTypeConfigurable = $catalogProductTypeConfigurable;
    parent::__construct($context, $data);
}

public function getProductData($id) {
    $parentByChild = $this->_catalogProductTypeConfigurable->getParentIdsByChild($id);
    if (isset($parentByChild[0])) {
        //set id as parent product id...
        $id = $parentByChild[0];
    }
    return $id;
}
2
  • Parent class not specified! I think its Magento\Catalog\Block\Product\AbstractProduct??? Nov 24, 2016 at 13:21
  • You could also use \Magento\ConfigurableProduct\Model\Product\Type\Configurable instead of resource model
    – LucScu
    Jan 21, 2021 at 10:54

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy