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.

  • Please check my answer and let me know. – Rohan Hapani Sep 13 '18 at 8:57
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.

| improve this answer | |
  • yes i have injected model and working fine. Thanks @sukumar – Sanjay Vadadoriya Sep 13 '18 at 11:01
  • Welcome. Happy Coding :) – Sukumar Gorai Sep 13 '18 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();
}
| improve this answer | |

Your Answer

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

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