如果我有以下两个域
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()
答案 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()