I need to manipulate a custom product attribute for almost all products in the database. Right now I have this:

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

        foreach ($productsCollection as $_product) {
            $product = Mage::getModel('catalog/product')->load($_product->getEntityId());
            if ($product->getCustomizableonly() === null) {
                $product->setData('customizableonly', 0)->getResource()->saveAttribute($product, 'customizableonly');

But the products are more than 2000 and therefore I don't want to load the product object itself, but to work just with the product object instance from the collection. The problem is that this obj. instance contains only 1/9th of the whole Data of the product object itself. And the 'customizableonly' attribute is NOT part of that 1/9th.

How can I access the attribute without making unnecessary object loading. Or in general - how can this code be optimized to maximum, so it is not dramatically slow in case of 2000+ products?

1 Answer 1


Get your collection like this.

$productsCollection = Mage::getModel('catalog/product')->getCollection()->addAttributeToSelect('customizableonly');

And here is an other way of updating all products at once so you don't have to call saveAttribute 2k times.
From what I understand, you want to set the value for customizableonly to 0 for all the products that don't have that value.
Here goes:

$toUpdate = array();
foreach ($productsCollection as $_product) {
    if (is_null($_product->getCustomizableonly())) {
        //remember the id for update
        $toUpdate[] = $_product->getId();

//update all products
Mage::getSingleton('catalog/product_action')->updateAttributes($toUpdate, array('customizableonly'=>0), 0);  

This should get you a boost in speed.

  • Excellent answer. Thanks a lot! I just want to ask - in the 2nd solution I get an exception Call to a member function getAttributeId() on a non-object in **C:\htdocs\hach_gk\app\code\core\Mage\Catalog\Model\Resource\Product\Action.php** on line **69**. By debugging I found that the previous line $attribute = $this->getAttribute($attrCode); returns false. It cannot find the attribute or what ?
    – Syspect
    Jan 31, 2014 at 14:05
  • I think it tries to update an attribute value for a product that does not have that attribute. I mean, the product belongs to an attribute set that does not contain the attribute. And there are not 2 solutions. You should use both. Get the collection like I described, then loop through it and get the products for update.
    – Marius
    Jan 31, 2014 at 14:08

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.