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.
Happy coding 🙂
You can also check a complete list of our Magento 2 extensions.
2 comments