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开发者_Go百科 to know what items are common to both collections for a given Emp (itemsell and itembuy); how can I do such iteration?
Thanks
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
Use the findAll method on one of the collections. Something like this:
def similarItems(itemsell, itembuy) {
itemsell.findAll{ sell -> itembuy.contains(sell) }
}
精彩评论