Reputation: 14862
I am looking for a way to filter the products being returned on a category page by the current category AND an optional sub-category. Every solution I have seen so far has been 'show products that are in category-a OR category-b'.
Which file do I need to edit to filter a product collection by an additional, optional category id passed as a query parameter (e.g. ?catfilter=32
)?
Upvotes: 1
Views: 7223
Reputation: 11
About error Item (Mage_Catalog_Model_Product) with the same id "30674" already exist' in /magento/lib/Varien/Data/Collection.php:373, I found the solution:
$conditions = array();
foreach ($categoryIds as $categoryId) {
if (is_numeric($categoryId)) {
$conditions[] = "{{table}}.category_id = $categoryId";
}
}
$collection->distinct(true)
->joinField('category_id', 'catalog/category_product', /* 'category_id' */null,
'product_id = entity_id', implode(" OR ", $conditions), 'inner');
Upvotes: 1
Reputation: 12809
look here: http://vibrantdrive.com/how-to-filter-magento-products-using-2-or-more-category-filters/
To get products in Category 4 AND category 5
$_productCollection = Mage::getModel('catalog/product')
->getCollection()
->joinField('category_id', 'catalog/category_product', 'category_id', 'product_id = entity_id', null, 'left')
->addAttributeToSelect('*')
->addAttributeToFilter('category_id', array(
array('finset' => '4'),
array('finset' => '5'))
)
->addAttributeToSort('created_at', 'desc');
To get product in Category 4 OR category 5
$_productCollection = Mage::getModel('catalog/product')
->getCollection()
->joinField('category_id', 'catalog/category_product', 'category_id', 'product_id = entity_id', null, 'left')
->addAttributeToSelect('*')
->addAttributeToFilter('category_id', array(
array('finset' => array('4', '5')),
)
->addAttributeToSort('created_at', 'desc');
Upvotes: 6