尝试创建具有FK关系的grails域对象
所以我试图在BootStrap.groovy中加载一些测试数据,但是我在创建一个具有一对多FK关系的对象时遇到了问题 以下是域类(示例): 而且尝试创建具有FK关系的grails域对象,grails,gorm,Grails,Gorm,所以我试图在BootStrap.groovy中加载一些测试数据,但是我在创建一个具有一对多FK关系的对象时遇到了问题 以下是域类(示例): 而且 class BookCategory { static belongsTo = Book static hasMany = [books : Book] String name } 在Bootstrap.groovy中: def romanceCat = new BookCategory(name: 'Roman
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等。您需要在
书籍中定义BookCategory
属性的名称:
class Book {
static hasOne = [bookCategory:BookCategory]
}
您的引导应该是:
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)
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)