Magento: How to filter product collection using 2 or more category filters?
Suppose, you have a product collection and you want to filter it by category. Suppose, you want to filter it by more than one category. You can use addCategoryFilter if you have only one category. But, what if you want to filter by more than one category?
Category ids are stored for product in a comma separated way. So, to filter product collection by more than one category, you have to use:
addAttributeToFilter(‘category_ids’,array(‘finset’=>$categoryIds));
$categoryIds can be a single category id or comma separated category ids.
The following code filters product collection by two category ids (36 and 37).
$_productCollection = Mage::getResourceModel('reports/product_collection')
->addAttributeToSelect('*')
->addAttributeToFilter('category_ids',array('finset'=>'36,37'));
finset does so… when we use finset, the mysql function find_in_set is used in the sql query by Magento.
mysql function find_in_set:
FIND_IN_SET() looks for the first occurrence of a string within another string containing comma-separated values.
SELECT FIND_IN_SET(‘b’,'a,b,c,d’); // result = 2
For Magento version 1.4 and higher
$_productCollection = Mage::getModel('catalog/product')
->getCollection()
->joinField('category_id', 'catalog/category_product', 'category_id', 'product_id = entity_id', null, 'left')
->addAttributeToFilter('category_id', array('in' => array('finset' => '36,37')))
->addAttributeToSelect('*')
->setPageSize(5);
Cheers!
From Mukesh Chapagain's Blog, post Magento: How to filter product collection using 2 or more category filters?
Related posts:
- Magento: Get category name and url from product
- Magento: Get sub categories and product count
- Magento: How to search or filter by multiselect attribute in admin grid?
- Magento 1.4: No products displayed in category listing
- Magento: Get Product Collection by Type
- Magento: Very Useful Collection Functions
- Magento: Adding OR and AND query condition to collection
- Magento: Join, filter, select and sort attributes, fields and tables
- Magento: Get current and parent category
- Magento: Adding category attributes

Pingback: How to filter Magento product collection using 2 or more category filters?