Grails,gorm。通过 parent 查找 child,通过 child 查找 parent
Grails, gorm. Find child by parent and parent by child
例如,我parentclass作者:
class Author {
String name
static hasMany = [
fiction: Book,
nonFiction: Book
]
}
和一本childclass书:
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()
如何找到 parent 的 child-class 记录和 child 的 parent-class 记录?
在我看来,这不是对数据建模的最佳方式。我会这样做。
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)
例如,我parentclass作者:
class Author {
String name
static hasMany = [
fiction: Book,
nonFiction: Book
]
}
和一本childclass书:
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()
如何找到 parent 的 child-class 记录和 child 的 parent-class 记录?
在我看来,这不是对数据建模的最佳方式。我会这样做。
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)