Bulk Copying Product Attributes in Magento

Posted by | March 10, 2011 | Magento Code Snippets | No Comments

Disclaimer: this code was only tested on Magento 1.5.0.1 and we do not guarantee it will or will not work for you. Please use with caution…

This static method can copy attributes between products in Magento very fast and relatively secure. We are bypassing the main Magento architecture and accessing the Database directly, but notice we are using the Zend framework for the db query and we still use DB transactions. It accepts the source product ID (not SKU), destination product ID, the array of attribute codes (‘size’, ‘color’, ‘name’, etc.), and the attribute type (‘varchar’, ‘int’, etc.).
public static function copyOrCreateAttributes( $srcId, $dstId, $arrayOfAttributes, $type='varchar' )
{
$write = Mage::getSingleton('core/resource')->getConnection('core_write');
$table = Mage::getSingleton('core/resource')->getTableName('catalog_product_entity_'.$type);

if (count($arrayOfAttributes)>0)
{
$write->beginTransaction();
try {

foreach ($arrayOfAttributes as $a)
{
$replace = “REPLACE INTO {$table} (entity_type_id,attribute_id,store_id,entity_id,value) “;
$replace.= “SELECT entity_type_id, attribute_id, store_id, “.$dstId.”, value “;
$replace.= “FROM “.$table.” WHERE entity_id=”.$srcId.” “;
$replace.= ” AND attribute_id=(SELECT attribute_id FROM eav_attribute “;
$replace.= “WHERE attribute_code=’”.$a.”‘ AND entity_type_id=4)”;

$write->query($replace);
}

//commit transaction or rollback
$write->commit();
} catch (Exception $e) {
$write->rollback();
$m = “copyAttributes: Error trying to copy attributes:\n”;
$m.= “srcId = $srcId\n”;
$m.= “dstId = $dstId\n”;
$m.= “Error message from exception: “. $e->getMessage() . “\n”;
$m.= $e->getTraceAsString();
Mage::log($m);
}
}
}