Magento 1.9 – Fix Uncaught Exception ‘Item with Same ID’ Error

fatal errormagento-1.9

I'm trying to generate a feed and the code [CODE] is working like a charm on store1 but generates an error [ERROR] on store2. When I skip the SKIPPING PART (see source) it works fine but I can't select catgeories anymore and all products are used

[ERROR]

Fatal error: Uncaught exception 'Exception' with message 'Item (Mage_Catalog_Model_Product) with the same id "171" already exist' in /home/huisent/public_html/staging/lib/Varien/Data/Collection.php:373 Stack trace: #0 /home/huisent/public_html/staging/app/code/core/Mage/Eav/Model/Entity/Collection/Abstract.php(265): Varien_Data_Collection->addItem(Object(Mage_Catalog_Model_Product)) #1 /home/huisent/public_html/staging/app/code/core/Mage/Eav/Model/Entity/Collection/Abstract.php(1055): Mage_Eav_Model_Entity_Collection_Abstract->addItem(Object(Mage_Catalog_Model_Product)) #2 /home/huisent/public_html/staging/app/code/core/Mage/Eav/Model/Entity/Collection/Abstract.php(871): Mage_Eav_Model_Entity_Collection_Abstract->_loadEntities(false, false) #3 /home/huisent/public_html/staging/lib/Varien/Data/Collection.php(741): Mage_Eav_Model_Entity_Collection_Abstract->load() #4 /home/huisent/public_html/staging/advertentieFeed/removeLF.php(94): Varien_Data_Collection->getIterator() #5 {main} thrown in /home/huisent/public_html/staging/lib/Varien/Data/Collection.php on line 373

[CODE]

require '../app/Mage.php';
Mage::app("default");

$products = Mage::getModel('catalog/product')->getCollection();
$products->joinField(
'qty',
'cataloginventory/stock_item',
'qty',
'product_id=entity_id',
'{{table}}.stock_id=1',
'left'
);

  //Id;Extra;Description;Price;Title;Image1;Image2;Image3;Image4;Image5;Image6;Image7;Image8;Url
$products->addAttributeToFilter('status', 1);
$products->addAttributeToFilter('visibility', 4);
$products->addAttributeToSelect('id');
$products->addAttributeToSelect('description');
$products->addAttributeToSelect('price');
$products->addAttributeToSelect('name');
$products->addAttributeToSelect('image');
$products->addAttributeToSelect('url');
$products->addAttributeToSelect('sku');
$products->addAttributeToSelect('media_gallery');

****/* SKIPPING PART BEGIN
*/****
 $products->joinField('category_id',
'catalog/category_product',
'category_id',
'product_id=entity_id',
null,
'left' 
);
*** END SKIPINNG PART ***

/* Selection of wanted categories */
$products->addAttributeToFilter('category_id', array('in' => array($CAT_ID1,$CAT_ID2,$CAT_ID3,$CAT_ID4,$CAT_ID5)));

Best Answer

I think the part where you're joining to category_product selects double items. Try adding a Zend_Db_Select::distinct() to the collection

$products->getSelect()->distinct();

or use a group by

$product->getSelect()->group('e.entity_id');