Mini Tutorial: Bug Fix for Magento Import – Replace Existing Product Data

In the Magento admin, System > Import/Export > Import, can be used to update Product Attributes such as Related Products using a CSV file:

sku,_links_related_sku
3807-8018,7007-0526
,8908-1305
,8905-1023
,8905-1389
3807-8202,6607-9398
,8908-1335
,8905-1331
,8905-1026

There are two options:

1) Append Complex Data – which will add the SKUs  from the csv to existing related products

2) Replace Existing Complex Data – deletes existing related products and adds the SKUs from the csv to the related products

One of our clients wanted to update Related Products, and noticed that the “Replace Existing Complex Data” doesn’t work. So even if you choose this option, upload the csv and run the import, the old related product entries remain.

After debugging, I noticed that the problem was in this file: app\code\core\Mage\ImportExport\Model\Import\Entity\Product.php, line 68:

$this->_connection->quoteInto(‘product_id IN (?)’, array_keys($productIds))

This line is part of a “DELETE” SQL statement which supposedly removes existing product links that you are trying to replace from the catalog_product_link table. But array_keys($productIds) won’t contain product id’s, rather, array indexes (0,1,2…). The correct code is array_values($productIds).

This fix ensures that old values are deleted from catalog_product_link table. However, there is a need to specify the type (Upsell, Related, Cross sell) of link is being updated. Otherwise, even if you are not updating Upsell or Cross sell, they will be reset for the SKU that is being processed. To fix this additional bug, create an a variable that will hold the link types to affect around line 18, before the “while” loop begins:

$linkTypesToAffect = array();

Then do this on line 53:

if(!in_array($linkId,$linkTypesToAffect)) {
array_push($linkTypesToAffect,$linkId);
}

This will collect the link types present in the csv file.

Lastly, change:

$this->_connection->quoteInto(‘product_id IN (?)’, array_keys($productIds))

to

$this->_connection->quoteInto(‘product_id IN (?) and link_type_id IN (‘.implode(‘,’,$linkTypesToAffect).’)’, array_values($productIds))
);

This will ensure that Magento will only affect the right link type, in this case, Related Products.

Once you’ve tested that these code changes fixes the bug in your Magento Version, revert app\code\core\Mage\ImportExport\Model\Import\Entity\Product.php, rewrite this class on a custom module, then apply the code changes.

(Working environment: Enterprise ver. 1.10.1.1, possibly applies to other previous and newer versions)