Domanda

I want to get total quantity of product added in cart by product ID. I use \Magento\Checkout\Model\Cart class to get all items in cart.

$items = $cart->getQuote()->getAllItems();

foreach ($items as $item) {
    if ($item->getProductId() == '101') {
        return $item->getQty(); //Get product qty
    }
}

This will get product qty added in cart. But if I have 30 products in cart it will loop 30 times.

Is there any way to get qty of single product without looping all products from cart?

Any help appreciated!

È stato utile?

Soluzione

You can directly get the total qty of quote without using foreach by using this method

$quote->getItemsQty();

If you want to check in order object then you can get it by,

$order->getTotalQtyOrdered()

Where $quote is Magento\Quote\Model\Quote object and

$order is Magento\Sales\Model\Order object.

Altri suggerimenti

//add code in list.phtml
<div>
    <?php
    $IdDoProduto = $_product->getId();
    $cart = $this->helper('\Magento\Checkout\Helper\Cart');
    $itens = $cart->getQuote()->getItems();

    foreach ($itens as $item){
        if($IdDoProduto == $item->getProduct_id()){
            echo $item->getQty();
        }
    }
    ?>
</div>

You can get item qty from bellow code it will check for the product in current item collection and return qty if product is available...

$items = $cart->getQuote()->getAllItems();
$productId="your_product_id";
foreach ( $items as $item) {
        if ($item->getProductId() == $productId) {
            return $item->getQty();
        }
    }
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a magento.stackexchange
scroll top