Associate products to all websites more performant

Recently I had to associate all products of a shop to newly created websites in a setup shell script (Associate products to all websites).

This could have been implemented like that:

<?php
/**
* Associates products to the newly created websites
*/
private function _associateProducts()
{
    $aWebsiteIDs = Mage::getModel('core/website')
                   ->getResourceCollection()
                   ->getAllIds();

    //remove default website
    array_shift($aWebsiteIDs);

    // bad way would have been:
        foreach (Mage::getModel('catalog/product')->getCollection() as 
                 $oProduct){
            $oProduct->setWebsiteIds($aWebsiteIDs)->save();
        }
        
}

A much better approach was it to use class Mage_Catalog_Model_Product_Action like that:

<?php
/**
* Associates products to the newly created websites
*/
private function _associateProducts()
{
    $aWebsiteIDs = Mage::getModel('core/website')
                   ->getResourceCollection()
                   ->getAllIds();

    //remove default website
    array_shift($aWebsiteIDs);

    //getAllIds();
    $aProductIds = Mage::getModel('catalog/product')
                   ->getResourceCollection()
                   ->getAllIds();

    // good way (better performance) @see Mage_Catalog_Model_Product_Action
    $oProductActionModdel = Mage::getSingleton('catalog/product_action');
    $oProductActionModdel->updateWebsites(
        $aProductIds,
        $aWebsiteIDs,
        'add'
    );
}

This was much more performant, than saving each product all the time.

By the way: The class Mage_Catalog_Model_Product_Action is really worth a glimpse., because it is really useful to update product attributes too!

Leave a Reply

Your email address will not be published.

 

This site uses Akismet to reduce spam. Learn how your comment data is processed.