您无法使用与库存项目模型相关的任何事件,因为Magento使用优化的SQL查询来一次减少所有订购项目的库存,从而绕过该模型。
我改写了Mage_CatalogInventory_Model_Stock
添加其他事件的位置来解决此问题:
<?php
/**
* Add events to observe stock qty change
*
* @author Fabian Schmengler
*
*/
class SGH_ShippingExpress_Model_CatalogInventory_Stock
extends Mage_CatalogInventory_Model_Stock
{
const EVENT_CORRECT_STOCK_ITEMS_QTY_BEFORE = 'cataloginventory_stock_item_correct_qty_before';
const EVENT_CORRECT_STOCK_ITEMS_QTY_AFTER = 'cataloginventory_stock_item_correct_qty_after';
/**
* (non-PHPdoc)
* @see Mage_CatalogInventory_Model_Stock::registerProductsSale()
*/
public function registerProductsSale($items)
{
Mage::dispatchEvent(self::EVENT_CORRECT_STOCK_ITEMS_QTY_BEFORE, array(
'stock' => $this,
'items_obj' => (object)array('items' => &$items),
'operator' => '-'
));
$result = parent::registerProductsSale($items);
Mage::dispatchEvent(self::EVENT_CORRECT_STOCK_ITEMS_QTY_AFTER, array(
'stock' => $this,
'items' => $items,
'fullsave_items' => $result,
'operator' => '-'
));
return $result;
}
/**
* (non-PHPdoc)
* @see Mage_CatalogInventory_Model_Stock::revertProductsSale()
*/
public function revertProductsSale($items)
{
Mage::dispatchEvent(self::EVENT_CORRECT_STOCK_ITEMS_QTY_BEFORE, array(
'stock' => $this,
'items_obj' => (object)array('items' => &$items),
'operator' => '+'
));
$result = parent::revertProductsSale($items);
Mage::dispatchEvent(self::EVENT_CORRECT_STOCK_ITEMS_QTY_AFTER, array(
'stock' => $this,
'items' => $items,
'fullsave_items' => $result,
'operator' => '+'
));
return $result;
}
}
然后观察者cataloginventory_stock_item_correct_qty_after
可以看起来像这样:
/**
* @var $items array array($productId => array('qty'=>$qty, 'item'=>$stockItem))
*/
$items = $observer->getItems();
foreach ($items as $productId => $item) {
$stockItem = $item['item'];
$product = $stockItem->getProduct();
// Do anything you need with $stockItem and $product here
}
我建议不要进行繁重的处理或进行额外的数据库调用(例如,这对于检测产品是否缺货是必要的),而应将产品添加到由cronjob处理的队列中,以最大程度地减少额外的加载时间。用户。