3

I want to get Group expired date by child product SKU which belong to that group.

My code is,

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$product = $this->_productRepository->get($productSku);

$parentProductId = $objectManager->create('Magento\GroupedProduct\Model\Product\Type\Grouped')
        ->getParentIdsByChild($product->getId());

$parentSku = ???

When I var_dump $parentProductId, it return empty array. Any help?

0

You should inject the \Magento\Catalog\Api\ProductRepositoryInterface in your class constructer instead of using the objectManager!

After that, you will be able to call the getById() method. You will now have access to all product relations.

Try this code in your Method:

    $product = $this->productRepository->getById(YOURPRODUCTID);


    /** @var \Magento\GroupedProduct\Model\ResourceModel\Product\Link $productLinks */
    $productLinks = $product->getProductLinks();
    $parent = $productLinks->getParentIdsByChild(
                                 $product->getId(),                             
                                 \Magento\GroupedProduct\Model\ResourceModel\Product\Link::LINK_TYPE_GROUPED
               );

And don't forget the Injection by Construct:

/**
 * YOUCLASS constructor.
 *
 * @param \Magento\Catalog\Api\ProductRepositoryInterface $productRepository
 */
public function __construct(\Magento\Catalog\Api\ProductRepositoryInterface $productRepository)
{
    $this->productRepository = $productRepository;
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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