Here we’ll learn that how to get configurable associated products id in magento2
Step1# : We’ll create Demo.php class file in app/code/NameSpace/ModuleName/Controller/Product
<?php namespace NameSpace\Modulename\Controller\Product; use Magento\Catalog\Model\Product; class Demo extends \Magento\Framework\App\Action\Action { /** * Product $product */ private $product; public function __construct( \Magento\Framework\App\Action\Context $context, Product $product ) { parent::__construct($context); $this->product = $product; } public function execute() { $id = 1; // id of a configurable product $configurable = $this->product->load($id); $children = $configurable ->getTypeInstance() ->getUsedProducts($configurable); foreach ($children as $child) { echo $child->getEntityId(); } } }
Here $child->getEntityId() will print the associated product ids.
But by using getUsedProducts() we will not get those associated products that are out of stock or disabled. So in place of it if we write
$children = $configurable ->getTypeInstance() ->getChildrenIds($configurable->getId());
then we can get all the associated product ids of that configurable product.
Thanks 🙂
Great snippet! I’m looking for the opposite. Get the parent SKU (configurable) from simple product id or product sku.