Friday, March 11, 2011

Merge two collections in Magento

Searched for the way to merge two Magento collections. Here is the interesting approach I've figured out. We can extract SELECT object from both collections and then use UNION to merge the results of these collections.

$selectFoo = Mage::getResourceModel('model/foo')->getSelect();
$selectBar= Mage::getResourceModel('model/bar')->getSelect();

$mergedFooBar = $selectFoo->union(array($selectBar));

Quick and dirty but anyway possibly someone can suggest any alternative solution?

6 comments:

  1. Why don't you load the collections and yank out the items from one, and stick it in the other using removeItemByKey() addItem()?

    This makes the assumption that your keys do not overlap.

    The only thing I do not like about the SQL method is that the fields (getData stuff) have to be the same for each collection.

    - Bryan

    ReplyDelete
    Replies
    1. well, you are right
      SQL requires to have exactly the same fields structure of collections but it works faster than removeItemByKey() addItem() method performed for each element.

      Anyway thanks for pointing out this method as it can be reasonable on small collections with different structure.

      Delete
  2. SO GOOD JOB ..........................

    Thank you.................

    Goods Lift
    Hoist Lift

    ReplyDelete
  3. Outstanding submit I enjoy ones content; appreciate how we explained as much as possible, your are performing a great job many of other folks like you as a result of in which style of helpful weblogs provide consciousness to help you relevant to many things. My spouse and i go through other sorts of exciting information sites from your sites and also I'm a lot fascinated with your running a blog knowledge, We furthermore started to create post and this also sort debate truly guide me personally away. We witout a doubt added your current site and also shared the internet websites in order to my fellow workers not just me personally yet them all like ones running a blog abilities, desire people compose more intriguing weblogs such as this one particular and best of luck for ones upcoming weblogs.
    Jimmy Wilson-Harley Davidson Clothes

    ReplyDelete
  4. Amazing blog very helpful I would like to get in touch please add me on skype : freeestylerr2385. For more details go to sankethpatel.com

    ReplyDelete