Update or add crosssell product

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:

$magentoID = $need_relate_product_id; 

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();

 

 

你可能感兴趣的:(update)