【问题标题】:How to find particular product quantity in cart?如何在购物车中找到特定的产品数量?
【发布时间】:2013-02-28 05:58:52
【问题描述】:

我有一个产品的产品 ID。我想从购物车中获取该产品的数量,如果它已经在购物车中(如果它存在于已登录的用户那里)。

如果用户(注册)用户将产品添加到购物车离开站点。然后在某个时间他登录回站点并将相同的产品添加到购物车。此时我想检查是否有相同的产品购物车和产品的数量是多少?

$cart_m = Mage::getModel('checkout/cart')->getQuote();

foreach ($cart_m->getAllItems() as $item)
{
    $cart_productId = $item->getProduct()->getId();
    $productPrice = $item->getProduct()->getPrice();
    $productQuantity = $item->getProduct()->getQty();//I want to get specific product quantity,If I have product ID

}

【问题讨论】:

  • if($cart_productId == $theIdIwant) $theQtyIWant = $productQuantity;

标签: magento


【解决方案1】:
$cart_m = Mage::getModel('checkout/cart')->getQuote();
$yourProductId = 10;
$needQty = 0; 
foreach ($cart_m->getAllItems() as $item)
{

    $cart_productId = $item->getProduct()->getId();
    $productPrice = $item->getProduct()->getPrice();
    $productQuantity = $item->getProduct()->getQty();

    if ($yourProductId == $cart_productId){
        $needQty = $productQuantity;
        break;
    }
}

if (!$needQty){
    echo "This Product Not In Cart";
}else{
    echo $needQty;
}

【讨论】:

  • 我使用了 $productQuantity = $item->getQty(); //获取产品数量感谢您的帮助。这对我有帮助。
  • $item->getProduct()->getQty() 不起作用,请改用:$item->getQty()
【解决方案2】:

您可以在不循环所有项目的情况下获取产品数量:

$quote = Mage::getSingleton('checkout/session')->getQuote();
$_item = $quote->getItemByProduct($product);
$qty = $_item->getQty();

【讨论】:

  • 如果产品不在购物车中,您会收到致命错误(致命错误:在布尔值上调用成员函数 getQty())。你最好使用: $_quote = Mage::getSingleton('checkout/session')->getQuote(); $_item = $_quote ? $_quote->getItemByProduct($_product) : false; $qty = $_item ? $_item->getQty() : 0;
猜你喜欢
  • 1970-01-01
  • 2017-12-10
  • 1970-01-01
  • 2018-07-31
  • 2021-11-27
  • 2016-02-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多