GORM多对多映射,可与其他字段连接

rks*_*rks 10 grails many-to-many grails-orm jointable

我正在使用遗留数据库,并且与一个连接表有多对多的关联,我已经在很大程度上解决了映射工作正常.但是还有一个列,如果是Book,作者模型可以说nm_author_books包含一个名为'royalty'的字段.问题是如何从任何方向访问此字段?

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'] } 
}
Run Code Online (Sandbox Code Playgroud)

如果nm_author_book表具有[nm_book_id,nm_author_id,royalty],访问版税的方式是什么?

hak*_*811 12

基本的想法是从1多对多变为2多对一:一本书有很多BookAuthorDetail,一个作者有很多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]
}
Run Code Online (Sandbox Code Playgroud)

要通过BookAuthorDetail访问版税,您可以: BookAuthorDetail.findAllByBookAndAuthor(bookInstance, authorInstance)


Jef*_*eck 7

您可以创建一个为连接表建模的域对象,而不是更改Book和Author的映射,而是让它们指向AuthorBookRoyalty域.

Class AuthorBookRoyalty {
  Author author
  Book book
  Long royalty
}

class Book {
  String title
  static belongsTo =Author
  Static hasMany[authors: AuthorBookRoyalty]
}
Run Code Online (Sandbox Code Playgroud)

做类似的作者,您现在可以处理版税.您可能需要调整连接表上的映射,使其映射到当前数据库.