开发者

Grails: GORM Many-to-Many and One-To-Many relationship Mapping

开发者 https://www.devze.com 2023-02-09 11:20 出处:网络
I\'m having some problems while implementing on one class two different types of relations to another class.

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:

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:

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)

Do you have any idea what is the correct way to achieve the needed be开发者_如何学Gohavior?


Try the "hasOne". It stores the FK in the child table and may get you around the circular dependency issue


Maybe mappedBy solves the problem. But I'm not sure I have only found examples with two m:n-relationships.


Check out the answer to my question Domain Class relationships. I believe your question may have an answer there.

0

精彩评论

暂无评论...
验证码 换一张
取 消