0
votes

In my magento store i need to filter my product collection by 2 categories.

I have searched online and found ways of doing this (see existing code below) but they filter multiple categories using an OR condition – is there any way to do this with an AND condition so the products have to be found in BOTH categories not just any of them?

I am currently using the code below:

$_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' => '26'),
        array('finset' => '63'))
    )
    ->addAttributeToSort('created_at', 'desc');

    foreach($_productCollection as $_product){
        echo $_product->getName()."<br/>";
    };

My product/category setup is:

products:

category 1 (ID 26)
category 2 (ID 63)

product A - found in category 1
product B - found in category 1 & 2
product C - found in category 1 & 2

So my current code below would output all 3 products where as i want it to only show products B and C

2
Thanks but had tried all the suggestions in the link without successodd_duck

2 Answers

1
votes

Ended up filtering by just the 1 category, and then on the for each output checking if the product id is present in the 2nd category. Not ideal but does the job for now

$_filter = 26;

foreach($_productCollection as $_product){
    $cats = $_product->getCategoryIds();
    if (in_array($_filter, $cats)):
        ....
    endif; 
}
1
votes

Have you tried applying the filters sequentially?

So replace this:

->addAttributeToFilter('category_id', array(
    array('finset' => '26'),
    array('finset' => '63'))
)

With this:

->addAttributeToFilter('category_id', array(array('finset' => '26')))
->addAttributeToFilter('category_id', array(array('finset' => '63')))

This is generally how Magento likes to apply AND filters to collections.