10

我正在使用遗留数据库,并且与一个连接表有一个多对多的关联,我已经在很大程度上解决了这个问题,因为映射工作正常。但是还有一个额外的列,如果是 Book,Author 模型可以说 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'] } 
}

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

4

2 回答 2

13

基本思想是从 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]
}

要通过 BookAuthorDetail 访问版税,您可以执行以下操作:BookAuthorDetail.findAllByBookAndAuthor(bookInstance, authorInstance)

于 2014-06-17T14:18:41.757 回答
7

您可以创建一个域对象来对连接表进行建模,这样您就不必更改 Book 和 Author 的映射,而是让它们指向 AuthorBookRoyalty 域。

Class AuthorBookRoyalty {
  Author author
  Book book
  Long royalty
}

class Book {
  String title
  static belongsTo =Author
  Static hasMany[authors: AuthorBookRoyalty]
}

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

于 2012-11-07T14:14:45.023 回答