I am relatively new to Grails/GORM and I have very less exposure to hibernate before this.
I am trying to map child objects to parent object in grails. I have multiple child objects to map. Child objects already exist in the database.
class Parent {
static hasMany = [children: Child]
}
class Child {
String name
}
I have tried the following steps,
def parentId = <a valid parent domain id>
def parent = Parent.get(parentId)
def children = Children.getAll([list of valid children ids])
I tried the addTo*
with a list of child objects and it did not work.
parent.addToChildren(children)
It mapped only the first element from the list.
I also tried the following snippet, it did not work either.
parent.children += children
parent.save(flush:true)
I wasn't able to find a way to do this without using a loop. I believe that I'm missing something here.
Try this: children.each { parent.addToChildren(it) }
The addTo
only accepts a single instance, not a list. So iterate the list and add the individual instances.