1

Is there a way to setup related products to do a two way relationship instead of just a one way relationship.

If I relate product a with b then b should be related to a automatically.

I get my products from an API and the API doesn't allow me to map products together that are the same except for flavor together. I'm hoping to be able to map the similar products together using related products.

Thanks

0

You can, but it requires customization. In general, this is how you set up related products programmatically: Programmatically Save Related Products. You follow up with $product->save().

However, note that if you hook onto catalog_product_save_before to load other products (for the two-way link) to save, you'll have an infinite loop of catalog_product_save_before. So, I recommend hooking onto catalog_product_save_after event to trigger another process that will take care of the reverse association.

Some pseudocode:

// In the observer...
$product = $observer->getEvent()->getProduct();
if ($product->getRelatedLinkData() && !empty($product->getRelatedLinkData()) {
    $this->runMyCustomMethod($product);
}        

// In runMyCustomMethod($product)
$id = $product->getId(); // entity ID of the original product that got saved
$associatedIds = $prouct->getRelatedLinkData();

// Go through each of the products that got associated to the original product
// and save a reverse link
foreach ($associatedIds as $productId => $stuff) {
    $product = Mage::getModel('catalog/product')->load($productId); 
    $newData = ...; // Get this product's related links and append $id to it
    $product->setRelatedLinkData($newData);
    $product->save();
}
// Note: this process can get very expensive due to each product model loads

This is using the factory method to load the product objects individually. I recommend creating a resource model and take advantage of Varien_Db_Select instead for direct updates, instead of getModel().

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.