Nicolas
Nicolas

Reputation: 81

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:

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 behavior?

Upvotes: 1

Views: 2430

Answers (3)

Sunny
Sunny

Reputation: 1239

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

Upvotes: 1

nathan
nathan

Reputation: 5733

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

Upvotes: 0

Medrod
Medrod

Reputation: 996

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

Upvotes: 0

Related Questions