如何获取购物车中配置项目的库存?

时间:2013-05-21 10:02:59

标签: php magento

使用简单的产品,我可以这样做:

$quote = Mage::getSingleton('checkout/session')->getQuote();
$item = $quote->getItemById($params['item']); // $params['item'] contains item id
$product = $item->getProduct();
$stockQty = (int)Mage::getModel('cataloginventory/stock_item')->loadByProduct($product)->getQty();

但是,如果该项目是已配置的产品,则会尝试获取其父级可配置产品的库存,在大多数情况下,该库存的库存为零。

如何获取已配置产品的库存数量,最好不要通过其可配置的父母子产品进行循环?

1 个答案:

答案 0 :(得分:3)

您可以设置一个变量来确定库存状态,具体取决于可配置产品的子库存状态:

$inStock = true;
$quote = Mage::getSingleton('checkout/session')->getQuote();
$cart = Mage::getModel('checkout/cart')->getQuote();

$item = $quote->getItemById($params['item']); // $params['item'] contains item id
$_product = $item->getProduct();
$configuredProduct = Mage::getModel('catalog/product_type_configurable')->setProduct($_product);
$children = $configuredProduct->getUsedProductCollection()->addAttributeToSelect("*")->addFilterByRequiredOptions();
foreach($children as $simpleProduct) {
    foreach ($cart->getAllItems() as $item) {
        if ($item->getProduct()->getId() != $simpleProduct->getId()) continue;

        $stockQty = (int)Mage::getModel('cataloginventory/stock_item')->loadByProduct($simpleProduct)->getQty();
        if ($stockQty <= 0) {
            $inStock = false;
            break;
        }
    }

}