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
Cheers!
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: Join, filter, select and sort attributes, fields and tables
- Magento: Get current and parent category
- Magento: Set Random Order in Collection using RAND()
- Magento: Adding category attributes
