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?

4 comments:

  1. Thanks for sharing your info. I really appreciate your efforts and I will be waiting for your further write ups thanks once again.
    Vee Eee Technologies

    ReplyDelete
  2. 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
  3. SO GOOD JOB ..........................

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

    Goods Lift
    Hoist Lift

    ReplyDelete

Zend Framework Development Blog
Look at my new project for ZF developers