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

2021-12-19 00:00:00 php magento

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

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!

推荐答案

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

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.

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

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

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

您可以看到 isInStock 检查了 status 属性,该属性在产品管理员的常规"部分中设置.

You can see that isInStock checks the status attribute, set in the "General" section of the Product admin.

试试这个

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

相关文章