Reading list Switch to dark mode

    How to get associated products from its configurable product

    Updated 26 March 2024

    How to get associated products from its configurable product

    Today we will see how to get associated products from its configurable product in magento 2.

    <?php
    
    namespace Webkul\Module\Controller\Product;
    
    use Magento\Catalog\Model\Product;
    
    class DemoClass 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. 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.

    I hope this helps.

    Searching for an experienced
    Magento 2 Company ?
    Find out More

    Happy coding 🙂

    You can also check a complete list of our Magento 2 extensions.

    . . .

    Leave a Comment

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


    2 comments

  • Jasvir Singh
    • Mohd. Faizan (Moderator)
  • Back to Top

    Message Sent!

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

    Back to Home