Magento 2 – Get Parent Product ID from Child Product ID for Configurable Products

configurable-productmagento2url

I have a configurable product with two virtual products as children. I have the child product ID. How can I the parent product ID from the child product ID?

I have tried this but it is not working

// the $parent is always empty
$parent = $childProduct->getTypeInstance()->getParentIdsByChild($childProductId);

Best Answer

Try following way:

$parentIds = $this->objectManager->get('Magento\ConfigurableProduct\Model\Product\Type\Configurable')
            ->getParentIdsByChild($productId);
$parentId = array_shift($parentIds);