2

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);
1
  • Added the code I have tried.
    – TFS
    Aug 31, 2016 at 15:32

2 Answers 2

7

Try following way:

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

Get Parent Product from Child Id.

protected $_productloader;
protected $configurable;
protected $grouped;
protected $bundleSelection;

public function __construct(
    ...........................................................
    \Magento\Catalog\Model\ProductFactory $_productloader,
    \Magento\ConfigurableProduct\Model\Product\Type\Configurable $configurable,
    \Magento\GroupedProduct\Model\Product\Type\Grouped $grouped,
    \Magento\Bundle\Model\Product\Type $bundleSelection,
    ...........................................................
) {
    ...........................................................
    $this->_productloader = $_productloader;
    $this->configurable = $configurable;
    $this->grouped = $grouped;
    $this->bundleSelection = $bundleSelection;
    ...........................................................
}

...........................................................
...........................................................
...........................................................

public function getParentProductData($productData)
{
    $prdData = '';
    $parentProductId = $this->getParentProductId($productData->getEntityId());
    if ($parentProductId) {
        $prdData = $this->_productloader->create()->load($parentProductId);
    } else {
        $prdData = $this->_productloader->create()->load($productData->getEntityId());
    }
    // parent Product Data
    return $prdData;
}

public function getParentProductId($childId)
{
    $parent_id = 0;
    // configurable product
    $product = $this->configurable->getParentIdsByChild($childId);
    if (isset($product[0])) {
        $parent_id = $product[0];
        return $parent_id;
    }
    // group product
    $groupIds = $this->grouped->getParentIdsByChild($childId);
    if (isset($groupIds[0])) {
        $parent_id = $groupIds[0];
        return $parent_id;
    }
    // bundel product
    $budel_id = $this->bundleSelection->getParentIdsByChild($childId);
    if (isset($budel_id[0])) {
        $parent_id = $budel_id[0];
        return $parent_id;
    }
    return $parent_id;
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.