Php 以编程方式在购物车中添加产品-空购物车

Php 以编程方式在购物车中添加产品-空购物车,php,magento,cart,Php,Magento,Cart,我正在尝试在购物车中添加产品,但购物车仍然为空。 这是我的密码 try{ $product_model = Mage::getSingleton('catalog/product'); // Load product $_sku = "1-574#AD-B00731"; $my_product_id = $product_model->getIdBySku($_sku); $my_product = $product_model->

我正在尝试在购物车中添加产品,但购物车仍然为空。 这是我的密码

try{
    $product_model = Mage::getSingleton('catalog/product');

    // Load product
    $_sku = "1-574#AD-B00731";
    $my_product_id  = $product_model->getIdBySku($_sku);
    $my_product     = $product_model->load($my_product_id);
    $qty_value = 1;

    // Add to cart 
    $cart = Mage::getModel('checkout/cart');
    $cart->init();
    $cart->addProduct($my_product, array('qty' => $qty_value));
    $cart->save();
    print_r($cart->getItemsQty().PHP_EOL);
    Mage::getSingleton('checkout/session')->setCartWasUpdated(true);
    var_dump("working");
 }
catch(Exception $e){
    return $e->getMessage();
}
当我打印
$cart->getItemsQty()
时,我的商品数量正在增加,但我的购物车仍然是空的。我认为它是
Mage::getSingleton('checkout/session')->setCartWasUpdated(true)工作不正常

有人知道什么不起作用吗

编辑1:我使用Magento 1.8.0,因此通过url查询不起作用,因为form_键尝试更改

$cart = Mage::getModel('checkout/cart');


购物车是单例的,因为您的商店中只有一个购物车供一个用户使用,所有想要使用它的人都可以将其称为getSingleton,而无需创建新对象。如果您使用Mage::getModel('checkout/cart'),它将创建一个新对象。是的,它将允许您将报价保存到DB,但这将不是当前活动的客户购物车。

您需要刷新Itemcollection的itemcache。因为这也将从中删除报价模型,所以必须在之后添加它

$cart->getItems()->clear();
$cart->getItems()->setQuote($cart->getQuote());

如何获取客户的购物车?您是否按照我的建议更改了脚本?要获取当前客户购物车,请使用Mage::getSingleton('checkout/cart')->getQuote();或者Mage::getSingleton('checkout/session')->getQuote();是的,我做了,我的购物车仍然是空的。我刚刚覆盖了购物车控制器,现在我使用URL方法
$cart->getItems()->clear();
$cart->getItems()->setQuote($cart->getQuote());