views:

55

answers:

2

Hi, I have the following relationship between two domain classes:

class Emp {
  String name
  hasMany = [itemsell:Item, itembuy:Item]
}

class Item {
   String name
}

And I need to know what items are common to both collections for a given Emp (itemsell and itembuy); how can I do such iteration?

Thanks

+1  A: 

Use the findAll method on one of the collections. Something like this:

def similarItems(itemsell, itembuy) {
   itemsell.findAll{ sell -> itembuy.contains(sell) }
}
Javid Jamae
+4  A: 

Make these changes to the Emp class

class Emp {
  String name
  hasMany = [itemsell:Item, itembuy:Item]

  // Modifications
  Collection<Item> getCommonItems() {
      itemsell.intersect(itembuy)
  }    

  static transients = [ 'commonItems' ]
}

You can then call emp.commonItems to get the items in common. You should add commonItems to the transients list, so that GORM understands that this is not a persistent property

Don
Didn't know about intersect.. Love it!
Javid Jamae
Now that's elegance ... thanks
xain