xain
xain

Reputation: 13839

Domain class iteration in grails

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

Upvotes: 0

Views: 586

Answers (2)

Dónal
Dónal

Reputation: 187499

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

Upvotes: 4

Javid Jamae
Javid Jamae

Reputation: 8999

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

def similarItems(itemsell, itembuy) {
   itemsell.findAll{ sell -> itembuy.contains(sell) }
}

Upvotes: 1

Related Questions