Work with custom product attribute without loading the product object itself
-
16-10-2019 - |
سؤال
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?
المحلول
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.