Filtering Magento product collection by multiple categories using AND condition
-
12-12-2019 - |
Question
I trying to display a list of products in Magento based on multiple categories. I'm using the following code which works well:
$collection = Mage::getModel('catalog/product')->getCollection()
->addAttributeToSelect('id')
->addAttributeToSelect('sku')
->addAttributeToSelect('name')
->addAttributeToFilter('status', 1)
->addAttributeToFilter('visibility', 4)
->addStoreFilter();
$catfilters = "1981,1982,1983";
$conditions = array();
foreach ($catfilters as $categoryId) {
if (is_numeric($categoryId)) {
$conditions[] = "{{table}}.category_id = $categoryId";
}
}
$collection->distinct(true)
->joinField('category_id', 'catalog/category_product', null, 'product_id = entity_id', implode(" OR ", $conditions), 'inner');
This works well and lists all products with category 1981, 1982 and 1983. So far so good but I also would like to filter on a fourth category "1984" but this should be using an "AND" condition. In order words: (1981 OR 1982 OR 1983) AND (1984).
After having read up on it I believe I need to add another joinField but I'm not sure how it would be done. Any help would be really appreciated.
Solution
Haven't tested but maybe this will work:
$collection->distinct(true)
->joinField('category_id', 'catalog/category_product', null, 'product_id = entity_id', "(".implode(" OR ", $conditions).") AND ({{table}}.category_id = 1984)", 'inner');
Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange