0

如果我有两个域如下

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

1 回答 1

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()
于 2013-10-20T17:42:43.750 回答