所以我试图在BootStrap.groovy中加载一些测试数据,而我在创建一个具有一个多FK关系的对象时遇到了麻烦......
这些是域类(示例):
class Book {
static hasOne = BookCategory
String name
}
和...
class BookCategory {
static belongsTo = Book
static hasMany = [books : Book]
String name
}
并在Bootstrap.groovy中:
def romanceCat = new BookCategory(name: 'Romance').save(flush: true)
def horrorCat = new BookCategory(name: 'Horror').save(flush: true)
def firstBook = new Book(name: 'Kujo', category_id: horrorCat).save(flush: true)
这些类别是在postgres中创建的,但本书并非如此。我怀疑我没有正确的语法来引用我的新书()中的FK,但我似乎找不到类似的例子,并尝试了几种变体。即。 BookCategory:horrorCat,BookCategory.id:horrorCat等。
答案 0 :(得分:2)
您需要在BookCategory
中定义Book
属性的名称:
class Book {
static hasOne = [bookCategory:BookCategory]
}
你的Bootstrap应该是:
def romanceCat = new BookCategory(name: 'Romance').save(flush: true)
def horrorCat = new BookCategory(name: 'Horror').save(flush: true)
def firstBook = new Book(name: 'Kujo', bookCategory: horrorCat).save(flush: true)