Magento - 遍历类别中的所有产品,更改值并保存
Magento - Loop through all products in category, change value and save
我需要遍历特定类别中的所有产品,更改自定义属性,然后保存每个产品。
目前我有:
$_category = Mage::getModel('catalog/category')->load($_POST['id']);
$all_products = $_category->getProductCollection();
foreach ($all_products as $product) {
$product = Mage::getModel('catalog/product')->load($product->getId());
$product->setCustomAttribute(xxxx);
$product->save();
}
这是最佳做法吗?是否可以改进它以提高性能?每个系列平均包含 15-20 个产品,我的加载时间非常慢,甚至脚本超时。
我已经使用 set_time_limit(0);
尝试强制它通过,但我想我可以改进我的代码来阻止我必须这样做?最终每个集合可能有超过 100-200 个产品,所以现在需要找到一个好的表现
如果您正在对相同的属性和相同的值进行大量更新,请考虑尝试 updateAttributes
:
// Iterate over the foreach and get all the product ids into an array
// $attr = array("attribute_code" => "attribute_value");
Mage::getSingleton("catalog/product_action")->updateAttributes($productIds, $attr, $storeId);
应该会快很多。
我需要遍历特定类别中的所有产品,更改自定义属性,然后保存每个产品。
目前我有:
$_category = Mage::getModel('catalog/category')->load($_POST['id']);
$all_products = $_category->getProductCollection();
foreach ($all_products as $product) {
$product = Mage::getModel('catalog/product')->load($product->getId());
$product->setCustomAttribute(xxxx);
$product->save();
}
这是最佳做法吗?是否可以改进它以提高性能?每个系列平均包含 15-20 个产品,我的加载时间非常慢,甚至脚本超时。
我已经使用 set_time_limit(0);
尝试强制它通过,但我想我可以改进我的代码来阻止我必须这样做?最终每个集合可能有超过 100-200 个产品,所以现在需要找到一个好的表现
如果您正在对相同的属性和相同的值进行大量更新,请考虑尝试 updateAttributes
:
// Iterate over the foreach and get all the product ids into an array
// $attr = array("attribute_code" => "attribute_value");
Mage::getSingleton("catalog/product_action")->updateAttributes($productIds, $attr, $storeId);
应该会快很多。