Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Programmatically modify related products in magento

I'm trying to programmatically manipulate the product relations in a Magento store.

From what I've read, setRelatedLinkData should be the way to go.

As I simple test, I'm just trying to replace a products related products with nothing (i.e. an empty array), however it's not working - the product in question is still showing the related product in the backend.

The test code I'm working with is:

$product = Mage::getModel('catalog/product')->load($product->getId());
$linkData = array();
print_r($linkData);

$product->setRelatedLinkData($linkData);
echo "Save\n";

$r = $product->save();

As mentioned above however the product still has a related product when I reload it in the backend.

NOTE: I don't only want to remove related products, eventually I want to be able to add new ones as well, so a DELTE FROM... SQL query isn't what I am looking for. However if I can't get it to work to remove products, then it's certainly not going to work to add them, so one step at a time :-)

like image 914
Liam Wiltshire Avatar asked Dec 25 '22 23:12

Liam Wiltshire


1 Answers

The quickest way I can think of is to use the Link Resource:

app/code/core/Mage/Catalog/Model/Resource/Product/Link.php saveProductLinks

// sample code

$product = Mage::getModel('catalog/product')->load(147);
$linkData = array();

Mage::getResourceModel('catalog/product_link')->saveProductLinks(
    $product, $linkData, Mage_Catalog_Model_Product_Link::LINK_TYPE_RELATED
);

and if you want to assign products use the same code but provide this as $linkData:

$linkData = array( 
    '145' => array('position' => 1), 
    '146' => array('position' => 2) 
);
like image 132
Adrian Marina Avatar answered Jan 05 '23 01:01

Adrian Marina