This tutorial explains how to assign related products magento 1 programmatically. The CSV file contain the products sku and related product sku’s

Please also refer how to import product programmatically and other magento tutorials.The below code assign the related product as shown below.
- Initialise database connection
- Read CSV data
- Assign related products magento 1
Initialise database connection
Create the relatedproducts.php inside the root and add the following code.
Read CSV data
Assign related products magento 1
function addRelatedProducts( $imported_products ) {
foreach($imported_products as $imported_product) {
$product = Mage::getModel(‘catalog/product’)->loadByAttribute(‘sku’, $imported_product[0]);
if($product)
{
$sRelatedSkus = $imported_product[25];
$sRelatedSku = explode(‘,’, $sRelatedSkus);
$aParams = array();
$nRelatedCounter = 1;
foreach( $sRelatedSku as $sku )
{
$aRelatedProduct = Mage::getModel(‘catalog/product’)->loadByAttribute(‘sku’, $sku);
if(is_object($aRelatedProduct)) {
$aParams[$aRelatedProduct->getId()] = array(‘position’ => $nRelatedCounter);
$nRelatedCounter++;
}
else {
echo ‘Sku not existing : ‘.$sku.PHP_EOL;
}
}
$product->setRelatedLinkData($aParams);
if($product->save())
echo ‘ Related products assigned for ‘. $imported_product[0].‘ ‘ . $product->getName().PHP_EOL;
}
}
}