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?

  • Can You be More specific About getting child products from product @Sri – Learing_Coder May 12 '18 at 8:57
1

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.

  • 3
    please do not use objectManager because u can inject class in constructor function. – Manish Goswami May 15 '18 at 10:04
  • 2
    Inject this class in contructor \Magento\Catalog\Model\Product and initiate it. – Manish Goswami May 15 '18 at 10:09
-1
$_children = $_product->getTypeInstance()->getUsedProducts($_product);
foreach ($_children as $child){
   $childProducts[] = $child;
}

$_product has the product object that is loaded by the corresponding ID

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.