Filter product collection by multiple categories in Magento

During the past week I’ve dealed with a very weird and stressing thing with my colleagues: filtering a product collection by multiple categories in Magento.

Filter by only 1 category

Magento offers a type of filter that can be used directly from the collection:

$_category = Mage::getModel(‘catalog/category’)->load($category_id);

$collection->addCategoryFilter($_category);

Filter by 2 or more categories

This is a completely different story. It’s very important to proceed correctly in order to avoid errors of the type:
[blockquote]Item (Mage_Catalog_Model_Product) with the same id already exist[/blockquote]

Proceed in the following way:

1. Call your collection and filter by the attributes you want to filter (all but the category one). For example:

$collection= Mage::getResourceModel(‘catalog/product_collection’)

->addFieldToFilter(‘is_saleable’,1)

->addFieldToFilter(‘type_id’, array(‘eq’ => ‘configurable’));

2. After doing this, you can apply your multiple category filter as follows: