GORM many-to-many mapping and combined with an optional field

I work with an outdated database and have a many-to-many relationship with the join table, which I decided to a large extent, since the mappings work fine. But there is an additional column, and in the case of the book "Model of the book, the author", we can say that in the nm_author_books contains the field "royalty". The question is, how do I access this field in 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 royalties?

+8
grails gorm many-to-many jointable
source share
2 answers

You can create a domain object that models the join of the table, instead of changing the mapping for the book and the author, you 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 the same for the author, and now you can deal with royalties. You may need to configure the mapping in the connection table so that it appears in your current database.

+7
source share

The main idea is the transition from 1 many-to-many to 2-to-one: the book has a lot of BookAuthorDetail, and the author has a lot of BookAuthorDetail

 class Book { String title static hasMany = [details: BookAuthorDetail] } class Author { String name static hasMany = [details: BookAuthorDetail] } class BookAuthorDetail { String royalty static belongsTo = [book: Book, author: Author] } 

to access royalty from BookAuthorDetail, you can do: BookAuthorDetail.findAllByBookAndAuthor(bookInstance, authorInstance)

+11
source share

All Articles