例如,我是父类作者:
class Author {
String name
static hasMany = [
fiction: Book,
nonFiction: Book
]
}
和一个儿童班书:
class Book {
String title
static belongsTo = [author: Author]
}
我使用以下方式为作者做了一些记录:
def fictBook = new Book(title: "IT")
def nonFictBook = new Book(title: "On Writing: A Memoir of the Craft")
def a = new Author(name: "Stephen King")
.addToFiction(fictBook)
.addToNonFiction(nonFictBook)
.save()
我怎样才能通过孩子的父母和父母类记录找到孩子级记录?
答案 0 :(得分:4)
在我看来,这不是建模数据的最佳方式。我会这样做。
class Author {
String name
static hasMany = [books: Book]
}
class Book {
String title
BookTypes bookType
static belongsTo = [author: Author]
}
enum BookTypes {
FICTION,
NON_FICTION
}
然后,你可以进行像
这样的查找def author = Author.get(1)
def nonFictionByAuthor = Book.findAllByAuthorAndBookType(author, BookTypes.NON_FICTION)
你也可以这样做......
def author = Author.get(1)
def fictionBooks = author.books.findAll { it.bookType == BookTypes.FICTION }
然后反过来说:
def fictionBook = Book.findByTitleAndBookType('Title001', BookTypes.FICTION)