I need to write to mysql database related products and upsells. This should be done by php. I can now set this for 1 product, but need to loop through all the products. My script:


require_once "blablabla/app/Mage.php";//my path here

$sku="876297-6";  //some Sku
$_product = Mage::getModel('catalog/product')->loadByAttribute('sku',$sku);

$param = array(

echo "Great!!";


What I cannot do is the following:

1.Get all product IDs 2.For each product ID set a related product as a random product from collection

Position does not matter at all. + do this until there are 20 related products would be cool, but I can also run script 20 times, no pressure. Better to work with product IDs and not skus.

My script is just example. main purpose is to set 20 random related products to each product Thanks in advance!

  • so, what you basically need is to set for each product 2 (or more) related products, right? Always the same products. From your script I understand you need to set the products with ids 101 and 102 as related products to all the other products. Did I get it right?
    – Marius
    Jul 28, 2015 at 15:28
  • my script is just example.. main purpose is to set 20 random related products to each product Jul 28, 2015 at 15:29

2 Answers 2


looping through all products using the Magento ORM is not the best idea. It's really time consuming.
Try instead to get all the ids and then run a simple sql query that will insert a row in the database.

Here is how you can get all the ids:

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

Once you know what product needs to be added as related for an other product do this:
Let's say that $mainId is the id of the main product and $relatedId is the id of the related product.

"INSERT into catalog_product_link SET 
    product_id = $mainId,
    linked_product_id = $relatedId,
    link_type_id = 1

1 is the link type id for related products.

  • How can i only get the product id's for the category page i'm currently on?
    – Head
    Apr 6, 2016 at 20:07

Final script, made by AreDubya:


require_once "/blablabla/app/Mage.php";//my path


$resource = Mage::getSingleton('core/resource');

$writeConnection = $resource->getConnection('core_write');

$ids = Mage::getModel('catalog/product')->getCollection()->getAllIds();
foreach ($ids as $id) {
    $mainId = $id;
    $relatedId = $ids[array_rand($ids)];
    echo "$id - $relatedId<br/>";
    $query = "INSERT into catalog_product_link (product_id,linked_product_id,link_type_id) VALUES ($mainId, $relatedId ,1)";


echo "done";


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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