Magento: How to Merge Two Product Collections into One

The way to merge two product collections into one

Posted on April 6, 2016 in Magento

If we have two product collections from two different categories, how can we merge them into one collection. For example,


$collection1 = Mage::getModel('catalog/category')->load(1)->getProductCollection();
$collection2 = Mage::getModel('catalog/category')->load(2)->getProductCollection();

# is there any method to do following thing?
$merged_collection = merge_collections($collection1, $collection2);

Almost every collection in Magento inherits from a Varien_Data_Collection. A collection is a special object that holds objects of another type. There’s no method for merging collections, but you can additional items of the appropriate type to the collection. Following is the one way to do the actual merging.


$collection1 = Mage::getModel('catalog/category')->load(1)->getProductCollection();
$collection2 = Mage::getModel('catalog/category')->load(2)->getProductCollection();

//load an empty collection (filter-less collections will auto-lazy-load everything)
$merged = Mage::getModel('catalog/product')->getCollection()->addFieldToFilter('entity_id', -1);

//add items from the first collection
foreach ($collection1 as $item) {
    $merged->addItem($item);
}

//add items from the second collection
foreach($collection2 as $item) {
    //magento won't let you add two of the same thing to a collection
    //make sure the item doesn't already exist
    if(!$merged->getItemById($item->getId()))
    {
        $merged->addItem($item);
    }
}

Some flat tables have a different primary key. So often you can generalize that with one of the collections’ getIdFieldName() method.


comments powered by Disqus