简体   繁体   中英

Grails - Copying hasMany relationships from one domain object to another?

During an archive process I am copying the details from an existing domain object to a new instance of that domain. Both domain objects have a hasMany relationship:

static hasMany = [pets:Pet]

When I have the following scenario:

def ownerOne = (logic to find owner)
def ownerTwo = new Owner
****ownerTwo.pets = ownerOne.pets****

How do I do that starred line? I've tired this:

Set<Pet> ownerTwoPets = new TreeSet<Pet>()
   for(Pet p : ownerOne.pets) {
      ownerTwoPets.add(p)
   }
ownerTwo.pets = ownerTwoPets

With no luck. I can do it with String objects in a hasMany without problem. But I cannot figure it out with domain objects in a hasMany

Grails has a built in method to add to a relationship like this one. Try this:

ownerOne.pets.each { Pet p ->
  ownerTwo.addToPets(p)
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM