9

How to get child product id's from parent product id in magento2 for configurable product?

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

1
  • Please check my answer and let me know. Commented Sep 13, 2018 at 8:57

2 Answers 2

4

Try the below solution:

<?php
    $productId = 5; //Configurable product ID
    $_objectManager = \Magento\Framework\App\ObjectManager::getInstance();
    $_product = $_objectManager->create('Magento\Catalog\Model\Product')->load($productId);
    $_childProducts = $_product->getTypeInstance()->getUsedProducts($_product);
    foreach ($_childProducts as $simpleProduct){
        echo $simpleProduct->getId();
    }
?>

Suggestion: Don't use object manager directly in your code as its not a best practice. You need to inject the product model class to your respective class then use it.

2
  • yes i have injected model and working fine. Thanks @sukumar Commented Sep 13, 2018 at 11:01
  • Welcome. Happy Coding :) Commented Sep 13, 2018 at 11:03
2

Try to use this code :

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$configProduct = $objectManager->create('Magento\Catalog\Model\Product')->load($product_id);

$_children = $configProduct->getTypeInstance()->getUsedProducts($configProduct);

foreach ($_children as $child){
    echo $child->getID();
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.