【问题标题】:Trying to create grails domain object with FK relationship尝试使用 FK 关系创建 grails 域对象
【发布时间】:2013-08-15 20:13:06
【问题描述】:

因此,我尝试在 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 中创建的,但本书不是。我怀疑我没有正确的语法来引用我的新 Book() 中的 FK,但我似乎找不到类似的示例并尝试了几种变体。 IE。 BookCategory:恐怖猫,BookCategory.id:恐怖猫等。

【问题讨论】:

    标签: grails grails-orm


    【解决方案1】:

    您需要在Book 中定义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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-05-05
      • 1970-01-01
      • 2019-03-24
      • 1970-01-01
      • 2015-06-07
      • 2016-06-22
      相关资源
      最近更新 更多