Как получить идентификатор товара после программного добавления товара в корзину?(Не в наблюдателе)


Я хочу программно добавить товар в корзину. Мой продукт добавляется с помощью следующего кода. Но он не вернул идентификатор элемента предложения. Как я могу получить идентификатор товара? Вот мой код

$id = 100;
$qty = '2'; 
$_product = Mage::getModel('catalog/product')->load($id);
$cart = Mage::getModel('checkout/cart');
$cart->init();
$cart->addProduct($_product, array('qty' => $qty));
$cart->save();
Mage::getSingleton('checkout/session')->setCartWasUpdated(true);
Author: Jancy Abraham, 2017-02-07

2 answers

Ваш код может быть дополнительно упрощен с помощью метода addProduct цитаты:

$id = 100;
$qty = 2;
$product = Mage::getModel('catalog/product')->load($id);
$quote = Mage::getSingleton('checkout/session')->getQuote();

//Returns the newly created quote item or an error
$quoteItem = $quote->addProduct($product, $qty);

//Collect totals and save the quote
$quote->collectTotals()->save();

//Grab the id from the new quote item
echo $quoteItem->getId();
 4
Author: Andrew Noble, 2017-02-07 07:45:09

Чтобы получить идентификатор предложения и идентификатор товара предложения, вы можете использовать приведенный ниже код.

$currentcart = Mage::getModel('checkout/cart');
$quote = $currentcart->getQuote();
$quoteItemId = $quote->getEntityId();

Чтобы получить идентификатор элемента предложения

$quoteItems = $quote->getAllVisibleItems();
foreach ($quoteItems as $item) {
    $ItemId = $item->getId();
}
 0
Author: BornCoder, 2017-02-07 07:23:14