代码之家  ›  专栏  ›  技术社区  ›  Stefan

在Grails和PostgreSQL中使用hasmany

  •  0
  • Stefan  · 技术社区  · 15 年前

    我有一个 《PostgreSQL》 具有此列结构的数据库:

    Author
      id
      name
    
    Book
      id
      name
      author_id
    

    以及抑制这些表的groovy域类:

    class Author {
       static hasMany = [ books : Book ]
    
       Integer id
       String name
    }   
    
    class Book {
       static belongsTo = Author
    
       Integer id
       Integer project_id
       String name
    }
    

    我的主要目标是从作者实例中获取书籍列表。

    author = Author.get( 1 ) // gets a author
    author.books // must return a list of books. 
    

    但这行不通。有什么明显的我做错了吗?

    笔记 我有很多Ruby/Rails经验和Zalava/Groovy经验。

    1 回复  |  直到 15 年前
        1
  •  2
  •   robbbert    15 年前

    改变你的 Book 类到:

    class Book {
       static belongsTo = [authors: Author]
    
       static mapping = {
           authors column: 'author_id'
       } 
    
       Integer id
       Integer project_id
       String name
    }
    

    如果不指定 mapping 与此类似,GORM将在默认情况下创建一个联接表。

    (顺便说一句,域类自动提供了一个“虚拟” id 属性(类型 Long 我想,翻译成 bigint 在PostgreSQL中)。无需手动指定,但也不会造成伤害。)


    编辑 :根据提问者的意见更新:

    如果一本书能 真的? 只有一个作者,你会在 班级:

    Author author
    static belongsTo = [author: Author]
    
    static mapping = { author column: 'author_id' } 
    

    可以找到一对多关系的GORM文档 here .

    推荐文章