Question

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

Was it helpful?

Solution

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);
            }
    
        }
    }
Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange
scroll top