Skip to content

Magento 1 Collections

Magento groupBy for collections

You might be running into exceptions being thrown, saying "Item (Mage_Catalog_Model_Product)" with the same id "*" already exist". And that is because multiple product records of the same item are added to collection, but that is not allowed.

Therefore you might think something like $collection->getSelect()->groupBy('e.entity_id') will solve the problem. Yes it will solve the problem, however if $collection->getSize() or $collection->count() is used anywhere in the project that now becomes 1 which might break things like pagination, etc.

Better solution would be to solve it with $collection->getSelect()->distinct(true) which would also get rid of duplicate items, and will not break any of Magento internal counting for collections.