gpt4 book ai didi

grails - Cereal ,哥伦。按 parent 找 child ,按 child 找 parent

转载 作者:行者123 更新时间:2023-12-02 14:19:09 28 4
gpt4 key购买 nike

例如,我有一个父类Author:

class Author {    
String name
static hasMany = [
fiction: Book,
nonFiction: Book
]
}

和一个 child 类的书:
class Book {    
String title
static belongsTo = [author: 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()

如何找到按父级分类的子级记录和按子级分类的父级记录?

最佳答案

我认为,这不是建模数据的最佳方法。我会这样做。

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) 

关于grails - Cereal ,哥伦。按 parent 找 child ,按 child 找 parent ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29707279/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com