Reading list Switch to dark mode

    How to get configurable associated products id in magento2

    Updated 20 February 2024

    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.

    Searching for an experienced
    Magento 2 Company ?
    Find out More

    Thanks 🙂

    . . .

    Leave a Comment

    Your email address will not be published. Required fields are marked*


    3 comments

  • Petter Granberg
    • Webkul Support
      • Petter Granberg
  • Back to Top

    Message Sent!

    If you have more details or questions, you can reply to the received confirmation email.

    Back to Home