這是一個有點棘手,有最有可能不包括在下面的代碼中的一些邊緣情況 - 同樣的答案,我們假設:
- 您希望降低庫存水平的所有相關產品父母剛剛購買
- 你希望只1
- 有必須滿足/處理
沒有進一步的併發症或其他條件,以減少
代碼:
所以,你顯然需要先創建一個模塊。 config.xml需要聲明將要監聽的觀察者checkout_type_onepage_save_order_after
。 (注:還有其他事件可以聽取以實現您的目標)。
config.xml文件將包含至少下面的代碼:
<?xml version="1.0"?>
<config>
<modules>
<YourCmpany_YourModule>
<version>1.0.0</version>
</YourCmpany_YourModule>
</modules>
<frontend>
<events>
<checkout_type_onepage_save_order_after>
<observers>
<yourmodule_save_order_observer>
<class>YourCompany_YourModule_Model_Observer</class>
<method>checkout_type_onepage_save_order_after</method>
</yourmodule_save_order_observer>
</observers>
</checkout_type_onepage_save_order_after>
</events>
</frontend>
<global>
<models>
<yourmodule>
<class>YourCompany_YourModule_Model</class>
</yourmodule>
</models>
</global>
</config>
然後在您的觀察:
<?php
class YourCompany_YourModule_Model_Observer
{
public function checkout_type_onepage_save_order_after(Varien_Event_Observer $observer)
{
$order = $observer->getEvent()->getOrder();
/**
* Grab all product ids from the order
*/
$productIds = array();
foreach ($order->getItemsCollection() as $item) {
$productIds[] = $item->getProductId();
}
foreach ($productIds as $productId) {
$product = Mage::getModel('catalog/product')
->setStoreId(Mage::app()->getStore()->getId())
->load($productId);
if (! $product->isConfigurable()) {
continue;
}
/**
* Grab all of the associated simple products
*/
$childProducts = Mage::getModel('catalog/product_type_configurable')
->getUsedProducts(null, $product);
foreach($childProducts as $childProduct) {
/**
* in_array check below, makes sure to exclude the simple product actually
* being sold as we dont want its stock level decreased twice :)
*/
if (! in_array($childProduct->getId(), $productIds)) {
/**
* Finally, load up the stock item and decrease its qty by 1
*/
$stockItem = Mage::getModel('cataloginventory/stock_item')
->loadByProduct($childProduct)
->subtractQty(1)
->save()
;
}
}
}
}
}
真棒男人謝謝!唯一的區別是我必須按照父母的銷售數量扣除子產品的數量。我確實有一個工作腳本,每次我在一系列訂單上運行它時都會這樣做,但我希望使用Observer使其更加無縫。把我有的和你寫的東西結合起來,我應該好好去! – jkphl
@Drew Hunter有什麼辦法可以減少訂購商品的數量,假設我有不同數量的訂單2產品,我想用相同的觀察者從庫存中減少相同的產品數量,有可能嗎? – Naveenbos