简体   繁体   English

Grails:GORM多对多和一对多关系映射

[英]Grails: GORM Many-to-Many and One-To-Many relationship Mapping

I'm having some problems while implementing on one class two different types of relations to another class. 在一个类上实现与另一类的两种不同类型的关系时,我遇到了一些问题。

As an example imagine an Author having a list of written books and then one which is his prefered one. 举例来说,假设一位作者拥有一份书面书籍清单,然后是他的首选书籍清单。

From the Grails GORM reference page I was able to implement the correct Many-to-Many relationship as follow: 在Grails GORM参考页上,我能够实现正确的多对多关系,如下所示:

class Author {
    static hasMany = [books: Book]
}

class Book {
    static belongsTo = Author
    static hasMany = [authors : Author]
}

Which is buy the way working perftectly. 这就是完美的工作方式。 The problem comes when I want to add the preferedBook relation to the Author class: 当我想将PreferredreferBook关系添加到Author类时,问题就来了:

class Author {
    Book prefered //My prefered book
    static hasMany = [books: Book]
}

This new line doesn't seem to work, there is an error at startup (while creating the tables) and then by saving the objects, not all relations are saved. 此新行似乎不起作用,启动时(创建表时)出现错误,然后通过保存对象,并不能保存所有关系。 (Even though they .save() method is being correctly called on all instances) (即使在所有实例上都正确调用了.save()方法)

Do you have any idea what is the correct way to achieve the needed behavior? 您是否知道实现所需行为的正确方法是什么?

Try the "hasOne". 尝试“ hasOne”。 It stores the FK in the child table and may get you around the circular dependency issue 它将FK存储在子表中,可能会带您解决循环依赖问题

Maybe mappedBy solves the problem. 也许mappedBy解决了这个问题。 But I'm not sure I have only found examples with two m:n-relationships. 但是我不确定我是否仅找到带有两个m:n关系的示例

Check out the answer to my question Domain Class relationships . 查看我的问题“ 域类关系”的答案。 I believe your question may have an answer there. 我相信您的问题在那里可能有答案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM