Magento2 Cart Quote – Updating Quote Item in Magento 2

cartmagento-2.1.4magento2quotequoteitem

I am trying to update quote item in magento2. But every time i am saving the item its creating a new item with the same quote id rather than updating it. Here is my code

    public function __construct(
            \Magento\Quote\Model\QuoteRepository $quoteRepo
        ){
            $this->_quoteRepo = $quoteRepo;
        }

public function updateItem(){
    $quote = $this->_quoteRepo->get('id here');
    foreach($quote->getAllVisibleItems() as $itemq){
    $itemq->setQty(5);
    $itemq->setPrice(20);
    $itemq->save();
    }
 }

But every time its saving an item.. a new item is getting generated. Dont know why. Also I couldn't find any class which explicitly load qoute item in magento2. Help will be appreciated.

In this question https://magento.stackexchange.com/questions/139298/how-to-save-quote-items-in-magento-2 they are setting the whole product… not trying to update it. When you set a product a new quote item will surely generate. But why its doing the same in case of updation.

Best Answer

I am not sure about my below solution:

  • May be you need to load Quote item object by item id
  • As you want set price then using setPrice() you cannot set your desire price for that cart item
$item = $quote->getItemById($item->getId());
if (!$item) {
  continue;
}
$item->setQty((double) $qty);
$item->setCustomPrice($price);
$item->setOriginalCustomPrice($price);
$item->getProduct()->setIsSuperMode(true);
$item->save(); 
Related Topic