1

A site I'm building is migrating product information which includes cross sells (which may be more than one). In a local database I have put information on product sku and entity ids. My script takes this information and creates the cross sells association. The problem I'm having is some cross sells on these products have been done manually and when running this script it will over write all of the existing cross sells.

My code is:

umask(0);
require_once '../app/Mage.php';
Mage::app('admin');  

$sql = "SELECT * FROM books2";
$query = mysql_query($sql);

while($row = mysql_fetch_array($query)){    

    $collection = Mage::getModel('catalog/product')->getCollection();

    $collection->addAttributeToSelect('*'); 
    $collection->addFieldToFilter(array(
    array('attribute'=>'sku',   'eq'=>$row['assocIsbn']),

    )); 

    echo "Looking at ".$row['assocIsbn']." relation prod id=".$row['magid']."<br/>";

    foreach ($collection as $product) {

        $magentoID = $row['magid'];

        $param = array(
               $magentoID=>array(
                      'position'=>1
                )
        );
        $product->setCrossSellLinkData($param);

        $product->save();

        echo "Updated ".$row['assocIsbn']." with rel3 product of ".$magentoID." <br/>";

        echo "<hr/>";
    } 

}

What I really need is for the cross sells products to be updated but not overwrite the existing cross sells products.

Any help is much appreciated.

5

You can build your $param array by merging the existing data with the products already assigned as crosssells.
You can get a list of the crosssels like this:

$crosssells = $product->getCrossSellProducts();

This will give you a collection with the products. To turn it int an array in the same form as $param you can do this

$param = array();
$crosssells = $product->getCrossSellProducts();
foreach ($crosssells as $item) {
    $param[$item->getId()] = array('position' => $item->getPosition());
}

Now you have in $param all the existing crosssels in a 'friendly' format.
All you need to do is to add your new crosssels:

if (!isset($param[$magentoID])){ //prevent elements from beeing overwritten
    $param[$magentoID]= array(
         'position'=>1
    )
}

After this just continue with your code:

$product->setCrossSellLinkData($param);
$product->save();
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.