我正在创建一个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中的数量。
您有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())
检查数量是否已经不好了…
请注意,这是未经测试的代码,并有一些反射来帮助你找到解决方案,我没有为你做这项工作。
亲切的问候,
我相信它会起作用的。试试这个。这是节省我的时间。
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();