Magento – How to get the child product ids from a product id in magento 2

configurable-productmagento2.2.2

How to get the child products id from a product id in magento 2.

I am saving the products with its custom attributes. And it saved successfully.
But

  1. I wish to check what type of product i have using a product id.
  2. If i have a simple product save the product as it is. But if it is a configurable product , I wish to get all the child products and need to assign the attributes to the child also.

So My question is How to check whether the product is simple or config ?

If it is configurable product, How to get its child product Ids?

Best Answer

This will get all child products (associated simple products) as an array of a configurable product by object manager.

$configProduct = $objectManager->create('Magento\Catalog\Model\Product')->load($product_id);

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

foreach ($_children as $child){
    echo "Here are your child Product Ids ".$child->getID()."\n";
}
echo "count: ".count($_children);

First, we load a configurable product by its product_id by object manager. You can get an array of associated simple products by simply calling getUsedProducts() from objects type instance.

You can also achieve it by creating Data.php class file in app/code/NameSpace/ModuleName/Helper

For more information click here.