这有点棘手,很可能下面的代码中没有涵盖一些边缘情况 - 答案也假设如下:
- 您希望减少刚刚购买的父级所有相关产品的库存水平
- 您只希望减少 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()
;
}
}
}
}
}