Php Magento:以编程方式更新购物车数量

Php Magento:以编程方式更新购物车数量,php,magento,e-commerce,magento-1.7,Php,Magento,E Commerce,Magento 1.7,我正在创建magento扩展。其中,我希望以编程方式更新购物车中的商品数量。我使用以下代码显示购物车中的项目 $quote = Mage::getSingleton('checkout/session')->getQuote(); $cartItems = $quote->getAllVisibleItems(); foreach ($cartItems as $item) { //Do something } 我想要的是更新特定产品的购物车数量。我知道可以这样做 $pid=1

我正在创建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循环的情况下更新一行I:e中的数量。

您有产品id,而不是项目id,对吗

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

查看
Mage\u Sales\u Model\u 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

要检查数量是否已经不好

请注意,这是未经测试的代码,一些反射可以帮助您找到解决方案,我没有为您做这项工作


亲切的问候,

我相信它会奏效的。试试这个。这是我的时间

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";
}
另一个解决方案

  $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();

如果我有商品id,那么我该怎么做?如果你有商品id,请删除前两行,并将其替换为$item=Mage::getModel('sales/quote\u item')->load($item\u id);和$pid=$item->getProductId();我必须这样修改才能让它工作:$quote->updateItem($itemId,array('qty'=>$qty));如果该项具有自定义选项,则当您强制仅更新QTY时将出现错误。请告诉我为什么会收到此消息-对非对象调用成员函数updateItem(),我已按原样复制了您的代码。您使用的是什么事件?检查此项:
  $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();