php 在产品上调用 isInStock() 方法的 Magento 问题

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2701599/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 07:24:43  来源:igfitidea点击:

Magento issue with calling isInStock() method on a product

phpmagento

提问by Nick Dima

I want to check if some products are in stock but whatever I do the isInStock()method always returns TRUE. My products are configurable products with no associated products and under the "Inventory" tab "Stock Availability" is set to "Out of Stock". What am I doing wrong? Thanks!

我想检查某些产品是否有库存,但无论我做什么,该isInStock()方法总是返回TRUE. 我的产品是没有关联产品的可配置产品,在“库存”选项卡下,“库存可用性”设置为“缺货”。我究竟做错了什么?谢谢!

回答by Alan Storm

Magento has a lot of history at this point, so it's a good idea to not always trust that method names will do what "seems obvious". Obvious now wasn't obvious a few years ago.

Magento 在这一点上有很多历史,所以不要总是相信方法名称会做“看起来很明显”的事情是个好主意。现在明显在几年前并不明显。

If you look at the following two methods on the Mage_Catalog_Model_Product class

如果在 Mage_Catalog_Model_Product 类上查看以下两个方法

public function isInStock()
{
    return $this->getStatus() == Mage_Catalog_Model_Product_Status::STATUS_ENABLED;
}
public function getStatus()
{
    return $this->_getData('status');
}

You can see that isInStockchecks the statusattribute, set in the "General" section of the Product admin.

您可以看到isInStock检查状态属性,在产品管理的“常规”部分中设置。

Try this instead

试试这个

$stockItem = $product->getStockItem();
if($stockItem->getIsInStock())
{
    //in stock!
}
else
{
    //not in stock!
}

回答by Mukesh

$qtyStock = Mage::getModel('cataloginventory/stock_item')->loadByProduct($_product)->getQty();

回答by Bakk László

<?php if ((int) Mage::getModel('cataloginventory/stock_item')->loadByProduct($_product)->getQty()>0) { ?>

 <?php  } else {} ?>

It worked for the simple product category view.

它适用于简单的产品类别视图。