Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/blackberry/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在grails和postgresql中使用hasMany_Grails_Groovy - Fatal编程技术网

在grails和postgresql中使用hasMany

在grails和postgresql中使用hasMany,grails,groovy,Grails,Groovy,我有一个具有以下列结构的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

我有一个具有以下列结构的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 = Author.get( 1 ) // gets a author
author.books // must return a list of books. 
但这是行不通的。有什么明显的错误吗


注意我有很多Ruby/Rails经验和zull Java/Groovy经验

将您的
书籍
课程更改为:

class Book {
   static belongsTo = [authors: Author]

   static mapping = {
       authors column: 'author_id'
   } 

   Integer id
   Integer project_id
   String name
}
如果您不这样指定
映射
,GORM将在默认情况下分别创建一个联接表

(顺便说一句,域类自动提供了一个“virtual”
id
属性(我认为是
Long
类型,在PostgreSQL中转换为
bigint
)。不必手动指定,但也不会有什么害处。)


编辑:根据提问者的评论更新:

如果一本书实际上只有一位作者,您应该在
book
类中声明:

Author author
static belongsTo = [author: Author]

static mapping = { author column: 'author_id' } 

可以找到关于一对多关系的GORM文档。

我将尝试此方法,但一本书有一位作者,而一位作者可能有许多书。。。。看起来像是你在设置一本
书。作者
?另外,你能给我指一下提到这一点的文档吗?(因为grails.org上的文档没有或至少…没有在表面上)请查看更新的答案。-在
create-drop
update
模式下定义数据库总是一个好主意(在一个附加的、实验性的项目中)要查看实际创建了哪个数据库模式。Robbert-如果您想查看当前域类的模式定义,只需运行“grails schema export”并查看target/ddl.sqlUnrelated,但您应该删除“Integer id”声明-grails为您添加id和版本属性。