Search code examples
grailsmany-to-manygrails-ormjoin

GORM many-to-many mapping and jointable with an additional field


I am working with legacy database and have a many-to-many association with a join-table that I have resolved to a large extent as the mappings are working fine. But there is an additional column and in case of Book, Author model lets say that the nm_author_books contain a field called 'royalty'. Question is how do I access this field from any direction?

class Book {
    String title
    static belongsTo = Author
    static hasMany = [authors: Author]
    static mapping = { authors joinTable: [name: "mm_author_books", key: 'mm_book_id' ] } 
}
class Author {
    String name
    static hasMany = [books: Book]
    static mapping = { books joinTable: [name: "mm_author_books", key: 'mm_author_id'] } 
}

If the nm_author_book table has [nm_book_id, nm_author_id, royalty] what is the way to access the royalty?


Solution

  • You could make a domain object that models that join table so instead of changing the mapping for Book and Author you have them point to the AuthorBookRoyalty domain.

    Class AuthorBookRoyalty {
      Author author
      Book book
      Long royalty
    }
    
    class Book {
      String title
      static belongsTo =Author
      Static hasMany[authors: AuthorBookRoyalty]
    }
    

    Do similar for Author and you can now deal with the royalties. You may need to adjust the mapping on the join table to make it map to your current database.