Magento 2:- Add a Grouped product programmatically

Follow my previous blogpost to create a simple product with magento that will give you a basic idea of creating products. In this blogpost we will continue from that post only. So to create product as grouped, we simply link some products to it.
In previous post code you also need to change type ID as grouped. Grouped product are added to link as related product are linked, below is the code that you need to add before saving product.

$childrenIds = array(53,54,55);
        $associated = array();
        $position = 0;
        foreach($childrenIds as $productId){
            //You need to load each product to get what you need in order to build $productLink
            $linkedProduct = $productRepository->getById($productId);
            /** @var \Magento\Catalog\Api\Data\ProductLinkInterface $productLink */
            $productLink = $objectManager->create(\Magento\Catalog\Api\Data\ProductLinkInterface::class);


            $associated[] = $productLink;

In below image you can see the data added to our product:-

Leave a Comment.