【问题标题】:Magento: Update cart quantity programmaticallyMagento:以编程方式更新购物车数量
【发布时间】:2013-03-01 06:49:33
【问题描述】:

我正在创建一个 magento 扩展。我想以编程方式更新购物车中的商品数量。我正在使用以下代码来显示购物车中的商品。

$quote = Mage::getSingleton('checkout/session')->getQuote();
$cartItems = $quote->getAllVisibleItems();
foreach ($cartItems as $item) {
  //Do something
}

我想要的是更新购物车上特定产品的数量。我知道可以这样做

$pid=15;
$quote = Mage::getSingleton('checkout/session')->getQuote();
$cartItems = $quote->getAllVisibleItems();
foreach ($cartItems as $item) {
if($pid==$item->getId())
$item->setQty($qty);
}

但我不喜欢这种方法,因为它会遍历每个产品来更新单个产品的数量。我想知道是否有一种方法可以在不使用 for 循环的情况下更新一行中的数量。

【问题讨论】:

标签: php magento e-commerce magento-1.7


【解决方案1】:

您有 product_id,而不是 item_id 对吗?

如果是这种情况,不执行整个项目就不可能获得产品ID。

看看Mage_Sales_Model_Quote::getItemByProduct($product);,你会发现它执行了整个目录。

基本上我会这样做:

//get Product 
$product = Mage::getModel('catalog/product')->load($pid);
//get Item
$item = $quote->getItemByProduct($product);

$quote->getCart()->updateItem(array($item->getId()=>array('qty'=>$qty)));
$quote->getCart()->save();

你应该用一些快速的技巧来优化它:

$quote->hasProductId($pid) to check if product is in the cart

($qty!=$item->getQty())

检查数量是否已经很好......

请注意,它是未经测试的代码,以及一些帮助您找到解决方案的反思,我没有为您完成这项工作。

亲切的问候,

【讨论】:

  • 如果我有商品 ID,我该怎么做?
  • 如果您有 item_id 删除前 2 行,并将其替换为 $item= Mage::getModel('sales/quote_item')->load($item_id);和 $pid = $item->getProductId();
  • 我必须像这样修改才能让它工作:$quote->updateItem($itemId, array('qty' => $qty));
  • 如果item有自定义选项,会报错,因为你只强制更新qty
  • 能否请您告诉我为什么收到此消息 - 在非对象上调用成员函数 updateItem(),我已按原样复制了您的代码。
【解决方案2】:

我相信它会起作用的。试试这个。这是节省我的时间。

public function updateCartAction(){
    $item_id = $this->getRequest()->getParam('item_id');
    $qty = $this->getRequest()->getParam('qty');

    $quote = Mage::getSingleton('checkout/session')->getQuote();
    $quote->updateItem($item_id, array( 'qty' => $qty));
    $quote->save();
    echo "Sssssss";
}

【讨论】:

    【解决方案3】:

    另一种解决方案

      $quote = Mage::getModel('sales/quote')->setStoreId($storeId)->load($cartid);
         $cartItems = $quote->getAllItems();
            foreach ($cartItems as $item) {
    
             if($cartiemid==$item->getId()){
                 $item->setQty($qty);
                 $item->save(); // you need to save the item after qty update
             }
    
            }
        $quote->save();
    

    【讨论】:

      猜你喜欢
      • 2012-12-31
      • 2014-07-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-10-20
      相关资源
      最近更新 更多