dsvq5069 2015-02-18 01:17
浏览 14
已采纳

在PHP中更新qty但在Magento中没有更新?

I've got this code below to retrieve and update 1 of the SKU of my Magento product.

It's updated and looks alright when I view on the code $product->getQty();

But when I look into Magento, the qty was not updated....

Could you please let me know where did I go wrong?

<?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>";
    };

?>
  • 写回答

1条回答 默认 最新

  • dongliling6336 2015-02-18 09:17
    关注

    The qty field isn't an attribute of the product model, it's only present because you're left-joining the stock_item table onto it. To update a quantity you need to update the instance of the stock_item model and save that. There's a handy helper function which lets you load a stock_item by a product ID.

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

    The reason your getQty output worked correctly afterwards is because the Model is a Varien_Object and therefore has the magic getter/setters which lets you save a variable called "Qty" on the model and retrieve it again later. However, having a variable on the model doesn't mean it will be attached to that database entry, only the attributes that are connected to the product entity will be saved when you call save().

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3