Magento 2 Configurable Product – Get Product Parent Name from Child Product

configurable-productmagento2product-collection

I have a product model from order item model, which i call like this:

$product = $orderItem->getProduct();

The problem is one of the order item is a child product from configurable product, i need to retrieve the parent name from this product, is there a way to do this?

Best Answer

Try this code:

$productId = 1; //this is child product id
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$product = $objectManager->create('Magento\ConfigurableProduct\Model\ResourceModel\Product\Type\Configurable')->getParentIdsByChild($productId);
if(isset($product[0])){
  $product = $objectManager->create('Magento\Catalog\Model\Product')->load($product[0]);
    echo $product->getName();
}