7
votes

Does anyone know if there is a way to run a product collection through a category filter twice? I have a ‘featured’ category, which is hidden, that I add products to so they’re available to grab as featured products. Currently I'm getting my product collection like this:

$_productCollection = Mage::getResourceModel('reports/product_collection')
    ->addAttributeToSelect('*')
    ->addAttributeToFilter('visibility', $visibility)
    ->addCategoryFilter('36');
    $_productCollection->load();

This works fine on the homepage, but on the category pages, I need to filter the results by the current category first, and then by the featured category:

$_productCollection = Mage::getResourceModel('reports/product_collection')
    ->addAttributeToSelect('*')
    ->addAttributeToFilter('visibility', $visibility)
    ->addCategoryFilter('15')
    ->addCategoryFilter('36');
    $_productCollection->load(); 

Unfortunately, it seems you can’t perform 2 category filters without editing core files, which I don’t want to do.

Any ideas how to get around this?

I was thinking I could maybe grab 2 product collections separately, one filtered by current category, and one by featured category, then using PHP's stristr find the products residing in both and use those, like

  if (stristr($featProductCollection, $currProductCollection))

Anyone any ideas? I think I’d need to return maybe just the SKU’s of the products, maybe in a comma separated list. But I’m not sure of the best way to go about this, and it does seem a bit hacky.

2
It helps tremensoudly with Magento problems if you can 1. Post an example of PHP code you're using to apply the filter 2. For any variables in the code, let people know the object's class There's not a proper consistent shared vocabulary among Magento developers, so giving people as much context as possible with help then figure out an answer.Alan Storm
Added some example code.Marlon Creative

2 Answers

6
votes

OK, actually sorted it myself with a bit of help from someone elsewhere:

    $_productCollection = Mage::getResourceModel('reports/product_collection')
    ->addAttributeToSelect('*')
    ->addAttributeToFilter('visibility', $visibility)
    ->addCategoryFilter($_category)
    ->addAttributeToFilter('category_ids',array('finset'=>'36'))
    $_productCollection->load();

Where $_category is the current category.

0
votes

Not sure why, but this doesn't work in 1.4, my solution was not very beautiful but work well on large database:

$select  = $collection->getSelect();
$select->where('(SELECT COUNT(1) FROM `catalog_category_product_index` AS `cat_index`
WHERE cat_index.product_id=e.entity_id AND cat_index.category_id
IN('.implode(',',$categories).') AND cat_index.store_id='.$collection->getStoreId().') >= '.count($categories));