gpt4 book ai didi

grails - 防止在条件语句中使用条件过滤器

转载 作者:行者123 更新时间:2023-12-02 15:28:21 26 4
gpt4 key购买 nike

我正在尝试做的一个例子是:

def authorName = "John Smith"
def books = Book.createCriteria().list() {
eq('genre', 'fiction')
eq('publishDate', '2007')
if(authorName != null){
Author author = Author.findWhere(name: authorName)
if( author == null ) //what do I do here?
else { eq('authorId', author.id }
}
}

如果没有给定ID的作者,则该作者不存在(假设未删除),因此该作者也没有写书。评估应在此处停止,并且不返回任何结果。我可以用什么来做到这一点?

最佳答案

我不是100%的尝试。如果您只想在作者存在的情况下执行Book查询,则可以这样...

def authorName = "John Smith"
Author author = Author.findWhere(name: authorName)
def books
if(author) {
books = Book.withCriteria {
eq('genre', 'fiction')
eq('publishDate', '2007')

// I can't tell if this is the right thing because
// I don't know what your model looks like, but I will
// assume this part is valid because it is what you had
// in your example.
eq 'authorId', author.id
}
}

根据模型的外观,您还可以只将authorName作为条件的一部分,这样就不必执行2个查询了。
def authorName = "John Smith"
def books = Book.withCriteria {
eq('genre', 'fiction')
eq('publishDate', '2007')
// this assumes that Book has a property named
// "author" which points to the Author
author {
eq 'name', authorName
}
}

关于grails - 防止在条件语句中使用条件过滤器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24296361/

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