Magento 1.9 – Fix ‘Item with Same ID Already Exists’ Error

event-observerjsonmagento-1.9

public function productDataToJson(Varien_Event_Observer $observer)
{
    $categoryModel = Mage::getModel('catalog/category');
    $treeModel = $categoryModel->getTreeModel();
    $categoryIds = $treeModel->getCollection()->getAllIds();
    $file = new Varien_Io_File();
    $jsonData = [];

    $productCollection = Mage::getResourceModel('catalog/product_collection');
    $productCollection->joinField(
        'category_id', 'catalog/category_product', 'category_id',
        'product_id = entity_id', null, 'left'
    );

    $productCollection->addAttributeToSelect('*')
        ->addAttributeToFilter('category_id', [
            ['in' => $categoryIds]
        ]);

    /**
     * Collect all the products we need to generate the required JSON
     */
    foreach ($productCollection as $product) {
        $productData = $product->getData();

        foreach ($productData as $attrCode => $attrVal) {
            if ($attrText = $product->getAttributeText($attrCode)) {
                $productData[$attrCode] = $attrText;
            }
        }

        $jsonData[] = array_merge(
            $productData,
            [
                'category_ids' => $product->getCategoryIds()
            ]
        );
    }

    /**
     * Split the results back out into the format you need
     */
    foreach ($categoryIds as $categoryId) {
        $categoryProducts = [];
        array_filter($jsonData, function ($item) use($categoryId, &$categoryProducts) {
            if (array_search($categoryId, $item['category_ids']) !== FALSE) {
                $categoryProducts[] = $item;
            }
        });

        $jsonResult = Mage::helper('core')->jsonEncode($jsonData);

        $file->open([
            'path' => Mage::getBaseDir() . '/jsondata/'
        ]);

        $file->write('/c_' . $categoryId . '_node.json', $jsonResult);
    }
}

I am getting all product details of particular category in different json files, need attribute texts of all attributes also dynamically created attributes. now it shows me this error :

Item (Mage_Catalog_Model_Product) with the same id "5" already exist

how can I solve this and get attribute labes and values in my json file?

Best Answer

I was facing the same problem. I have tried below solution its worked for me.

Solution:

Edit : /www/app/code/core/Mage/Eav/Model/Entity/Collection/Abstract.php Line: 256

Replace: return parent::addItem($object);

With: try { return parent::addItem($object); } catch (Exception $ex) { }
Related Topic