Request Quote

How to get associated products from its configurable product

How to get associated products from its configurable product

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

<?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(
        Product $product
    ) {
        $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.

Happy coding 🙂

. . .

Comment

Add Your Comment

Be the first to comment.

css.php
Hire Us!
Brief us about your requirements and we'll get back to you.
Woo! Hooy!
We have just recieved your project brief and our expert will contact you shortly.
Send Again
Close