Search code examples
grailsgrails-orm

Adding multiple childs belonging to a parent at once


If I have two domains as below

class Author {
  static hasMany = [books: Book]
  String name
}

class Book {
  static belongsTo = [author: Author]
  String color
}

How can I add multiple books for an author at the same time?

like Below:

def book1 = new Book(color: "white")
def book2 = new Book(color: "black")
def books = []
books << book1
books << book2

def author = new Author(name: "John Doe").addToBooks(books).save()

Solution

  • addToBooks takes either a Book instance or a map that can be used to create a Book instance. This is relatively compact:

    def book1 = new Book(color: "white")
    def book2 = new Book(color: "black")
    def books = []
    books << book1
    books << book2
    
    def author = new Author(name: "John Doe")
    books.each { author.addToBooks(it) }
    author.save()