0

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.

0

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');
  • That works perfectly, many thanks for quick answer! – user3429664 Apr 19 '15 at 11:41

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.