How to Get Bundle Product children in Magento 2 By Parent Id?
Bundle Product is generated from multiple simple or virtual product combinations in Magento 2.
You can get all the children items of bundle product by an interface, Magento\Bundle\Api\ProductLinkManagementInterface
Use getChildren() method from the above interface,
public function getChildren($productSku, $optionId = null);
Where,
$productSku is the Bundle product SKU,
$optionId is the option id of a bundle which you want to items for specific options.
If $optionId is null, all the children item will be loaded otherwise specific option id’s product will be loaded.
<?php namespace Jesadiya\ChildrenItem\Model; use Exception; use Psr\Log\LoggerInterface; use Magento\Bundle\Api\Data\LinkInterface; use Magento\Bundle\Api\ProductLinkManagementInterface; class ChildrenItem { /** * @var LoggerInterface */ private $logger; /** * @var ProductLinkManagementInterface */ private $productLinkManagement; public function __construct( LoggerInterface $logger, ProductLinkManagementInterface $productLinkManagement ) { $this->logger = $logger; $this->productLinkManagement = $productLinkManagement; } /** * Get all children items of bundle product * * @return LinkInterface[] */ public function getChildrenItems() { $sku = '24-WG080'; // Dynamic SKU try { $items = $this->productLinkManagement->getChildren($sku); } catch (Exception $exception) { throw new Exception($exception->getMessage()); } return $items; } }
Call from the template or Any PHP class,
$items = $this->getChildrenItems(); foreach ($items as $item) { var_dump($item->getData()); }
The result will be all assigned children items of a bundle.
Output:
array (size=10) 'entity_id' => string '26' (length=2) 'sku' => string '24-WG081-blue' (length=13) 'option_id' => string '1' (length=1) 'position' => string '1' (length=1) 'is_default' => string '1' (length=1) 'price' => null 'id' => string '1' (length=1) 'qty' => string '1.0000' (length=6) 'selection_can_change_quantity' => string '1' (length=1) 'price_type' => null array (size=10) 'entity_id' => string '29' (length=2) ........
Using the SKU value only, You can get the list of items available for the bundle.
To Retrieve the Get Configurable product children ids Magento 2.