Magento – Getting quote (cart) items programatically shows duplicate SKUs for both the configurable and simple product

addtocartcartmagento-1.9

I'm getting the shopping cart using:

$cart = Mage::getSingleton('checkout/session')->getQuote();

And then iterating through it using:

foreach ($cart->getAllItems() as $item) { }

But it seems to be returning duplicate items with the same SKUs, but different product ids! On the main site, when I open the cart, however, it shows the single product.

cart: {
    id: 680,
    items: [
        {
            name: "Tori Tank",
            price: "60.0000",
            id: "418",
            sku: "wbk004"
        },
        {
            name: "Tori Tank",
            price: "60.0000",
            id: "286",
            sku: "wbk004"
        }
    ]
}

My question is.. Why is this happening? Shouldn't the parent (configurable) product be showing its own unique Sku?

Also, if I want to add a product to the cart, should I add the configurable product? Or do I add the simple product and Magento handles the rest?

Best Answer

According to Magento, when a configurable product added at cart then two rows are inserted at the database. one configurable product cart another is a simple product

  • One row has configurable id and simple product SKU and parent item id is null
  • Other rows have simple id and simple product SKU and parent item id should above row id

As you have using getAllItems() then on for loop you need to check is it has parent item $item->getParentItemId().

foreach ($cart->getAllItems() as $item) {
    / * add this */
    if ($item->getParentItemId()) {
        continue;
    }
........
}
Related Topic