简体   繁体   English

Magento - 获取给定产品ID的购物车商品

[英]Magento - get cart items for a given product id

I try to get the cart items for a given product; 我尝试获取给定产品的购物车物品;

I have tried this code : 我试过这段代码:

$product = Mage::getModel('catalog/product')
    ->setStoreId(Mage::app()->getStore()->getId())
    ->load('2784');

$quote = Mage::getSingleton('checkout/cart')->getQuote();
$cartItems = $quote->getItemByProduct($product);
foreach ($cartItems as $item) {
    echo $item->getId()."<br/>";
}

but it don't gives anything. 但它没有给出任何东西。

How can I modify my code to use "getItemByProduct" in the right form ? 如何修改我的代码以正确的形式使用“getItemByProduct”?

Thanks for help. 感谢帮助。

getItemByProduct() returns the first matching Mage_Sales_Model_Quote_Item so there is no need for an extra loop. getItemByProduct()返回第一个匹配的Mage_Sales_Model_Quote_Item因此不需要额外的循环。

$item = $quote->getItemByProduct($product);
if ($item !== false) echo $item->getId();

You can not use getItemByProduct() function on the checkout/cart or checkout/quote model as that method is of the sales/quote model. 您不能在checkout/cartcheckout/quote模型上使用getItemByProduct()函数,因为该方法属于sales/quote模型。

You can find this method at the Mage_Sales_Model_Quote class . 您可以在Mage_Sales_Model_Quote class找到此方法。 so it is used withe sales/quote . 因此它用于sales/quote hope this is useful. 希望这很有用。

I'd use 我用了

foreach ($quote->getItems() as $item) {
    if ($item->getProductId() == $product->getId()) {
        print_r($item->getData());
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM