Magento – How to assign associate products to a grouped product programmatically

associate-productscreategrouped-productsmagento-1.8

I've created a grouped product programetically. And want too map associate products to it. I tried the following code which didn't work.
first way:

$gProduct->setGroupedLinkData(array($id1,$id2));

second way:

$gProduct->setAssociatedProducts(array($id1,$id2));

Any suggestions will be appreciated.

Thanks in advance.

Best Answer

Your associated products array should be like this

$data = array();
$data[$simpleId] = array('qty' => 9, 'position' => 0);
$data[$simple2Id] = array('qty' => 3, 'position' => 0);
$grouped->setGroupedLinkData($data);
$grouped->save();