更快地更新 collection 条记录

Updating collection records faster

我有 collection 条记录需要更新库存。我听说在 magento 上使用 "load" 会使它变慢,而且由于我在更新我的库存之前使用它,我想知道是否有更快的方法,因为我有数千种产品。

这是代码示例:

$productCollection = Mage::getResourceModel('catalog/product_collection')
                   ->addFieldToFilter(array(
                    array('attribute'=>'reference','neq'=>''),
    ));
//Update Prices and Stock
foreach ($productCollection as $product) {
 try {
    $reference = $product->getReference();
    $res = $products_api->xpath("item/sku[.='{$reference}']/parent::*"); 

    if (count($res) <= 0){
       unset($product);
       unset($res);
       unset($reference);
       continue;
    }

    $product->load($product->getId());
    //Search for Stock
    $stock = $res[0]->stocks->quantity;
    //Update Stock
    $product->setStockData(array(
                'use_config_manage_stock' => 0,
                'manage_stock'            => 1, 
                'is_in_stock'             => $stock > 0 ? 1 : 0,
                'qty'                     => $stock,
            ));

    $product->save();

您可以尝试使用库存项目加载而不是产品加载。请尝试使用以下代码:

$productCollection = Mage::getResourceModel('catalog/product_collection')
                   ->addFieldToFilter(array(
                    array('attribute'=>'reference','neq'=>''),
    ));
//Update Prices and Stock
foreach ($productCollection as $product) {
 try {
    $reference = $product->getReference();
    $res = $products_api->xpath("item/sku[.='{$reference}']/parent::*"); 

    if (count($res) <= 0){
       unset($product);
       unset($res);
       unset($reference);
       continue;
    }


    //Search for Stock
    $stock = $res[0]->stocks->quantity;
    //Update Stock

    $stockItem = Mage::getModel('cataloginventory/stock_item')->loadByProduct($product);
    if ($stockItem->getId()) {
        $isInStock = $stock > 0 ? 1 : 0;
        $stockItem->setQty($stock);
        $stockItem->setIsInStock($isInStock);
        $stockItem->setManageStock(1);
        $stockItem->setUseConfigManageStock(0);
        $stockItem->save();
    }

摘自 Sonassi 博客 - Magento 中的大量更新库存水平 - FAST