Magento 1.7 Filter products by multiple categories

青春壹個敷衍的年華 提交于 2019-12-01 12:58:10

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');

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');
  1. set distinct
  2. don't include the category_id field in select clause
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!