一次添加属于父项的多个子项

时间:2013-10-20 17:23:14

标签: grails gorm

如果我有以下两个域

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

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

如何同时为作者添加多本图书?

如下:

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()

1 个答案:

答案 0 :(得分:3)

addToBooks采用Book实例或可用于创建Book实例的地图。这是相对紧凑的:

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()