Magento – Merging two product collections by common elements (Inner join of two product collections (or two categories))

categorycollection;filter

I'm attempting to filter a product collection by two different category_ids. The solution i've come up involves generating two seperate product collections each filtered from the original by one category_id then merging them together. How does one merge product collections in this way? Let's take a look:

function categoryProductFilter($collection, $categoryIds){
        $collection->joinField('category_id',
            'catalog/category_product',
            'category_id',
            'product_id=entity_id',
            null,
            'left'
        );
        $categoryCollectionTwo = $collection->addAttributeToFilter(array(array('attribute' => 'category_id', 'finset' => 773)));
        $categoryCollectionOne = $collection->addAttributeToFilter(array(array('attribute' => 'category_id','finset' => 1550)));
        $collection=merge($categoryCollectionOne,$categoryCollectionTwo);
}
function merg($one,$two){??}

Is there an easier way to filter a product collection by two categories simultaneously? I've only managed to achieve mono-category filtering.

For reference:

$collection->addCategoryFilter(Mage::getModel('catalog/category')->load($categoryId), true);

Appears to filter the collection correctly as well as using some of the above methodology. It's almost absurd that the above cannot be used twice on the same collection to achieve appropriate filtering.

Best Answer

You need to make ONE collection, not 'merge two collections'.

With category object you can call getChildren to retrieve every child in a comma separated list (an array, not objects of sub-categories). Iterate as required.

You can convert this list of ids to an array, merge with another similarly derived array and implode the array back to the comma separated list of category IDs.

With this list of ids you can then run your collection, with the categories (that were only ever loaded as ids) put into the query with:

->addAttributeToFilter('category_id', array('in' => array('finset' => $cat_ids)))