在php中更新数量,但在Magento中未更新


Update qty in php but not updated in Magento?

我有下面的代码来检索和更新我的Magento产品的SKU 1。

当我查看代码$product->getQty()时,它已经更新,看起来还不错;

但当我查看Magento时,数量没有更新。。。。

你能告诉我哪里出了问题吗?

<?php
    define('MAGENTO_ROOT', dirname(__FILE__));
    $mageFilename = MAGENTO_ROOT . '/app/Mage.php';
    require_once $mageFilename;
    Varien_Profiler::enable();
    ini_set('display_errors', 1);
    umask(0);
    Mage::app();
    //get the collection filter the simple products & join the cataloginventory/stock_item table
    $collection = Mage::getModel('catalog/product')->getCollection()->addAttributeToSelect('sku')->addAttributeToFilter('type_id', 'simple')->joinField(
        'qty',
        'cataloginventory/stock_item',
        'qty',
        'product_id=entity_id',
        '{{table}}.stock_id=1',
        'left'
    ) ;
    ?>
    <html>
    <head></head>
    <body>
    <table>
    <?php 
    foreach ($collection as $product) {
        if ($product->getSku() == "test123") {
        try
            {
              $product->setData('qty', 99);
              $product->save();
            }
        catch (Exception $e)
            {
              echo $e->getMessage();
            }
        }
        echo "<tr><td>".$product->getSku()."</td><td> ".(int)$product->getQty()."</td></tr>";
    };
?>

数量字段不是产品模型的属性,它之所以存在,是因为您要将stock_item表连接到它上。要更新数量,您需要更新stock_item模型的实例并保存它。有一个方便的助手功能,可以通过产品ID加载stock_item。

$stockItem = Mage::getModel('cataloginventory/stock_item')->loadByProduct($myProductId);
if ($stockItem->getId()) {
    $stockItem->setQty($qty);
    $stockItem->save();
}

之后getQty输出正常工作的原因是,Model是Varien_Object,因此具有神奇的getter/setters,可以在模型上保存一个名为"Qty"的变量,然后再次检索。然而,在模型上有一个变量并不意味着它将附加到该数据库条目,当您调用save()时,只有连接到产品实体的属性才会被保存。

相关文章: