0

I have a child SKU in an array and I need to get all the parents from the existing child SKUs from the array. Can everybody help me ? Thanks

1

1 Answer 1

2

You cannot get parent SKU directly using child sku.

  • First, call \Magento\Catalog\Model\ResourceModel\Product::getIdBySku to get child product id by sky.
  • Then Parent product id by child Product id.\Magento\ConfigurableProduct\Model\ResourceModel\Product\Type\Configurable::getParentIdsByChild.

After that find parent skus by Parent Product id. \Magento\Catalog\Model\ResourceModel\Product::getProductsSku

Code Sample:

    /**
     * @var \Magento\Catalog\Model\ResourceModel\Product
     */
    private $resourceProduct;
    /**
     * @var \Magento\ConfigurableProduct\Model\ResourceModel\Product\Type\Configurable
     */
    private $resourceConfigurable;
    
    public function __construct(
        \Magento\Catalog\Model\ResourceModel\Product $resourceProduct,
        \Magento\ConfigurableProduct\Model\ResourceModel\Product\Type\Configurable $resourceConfigurable
    ){
        $this->resourceProduct = $resourceProduct;
        $this->resourceConfigurable = $resourceConfigurable;
    }
    
    public function test()
    {
        $childSku = 'child-MB-Configurable';
    
        $childId = $this->resourceProduct->getIdBySku($childSku);
    
        if ($childId) {
    
            $parentIds = $this->resourceConfigurable->getParentIdsByChild($childId);
            if (!empty($parentIds)) {
                $skus = $this->resourceProduct->getProductsSku($parentIds);
                echo '<pre>';
                print_r($skus);
            }
    
        }
    }

Your Answer

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

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