防止条件过滤器内部的联合语句

时间:2014-06-18 23:03:11

标签: grails groovy

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

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的作者,则作者不存在(假设它没有被删除),因此没有作者写的书。评估应该停在那里,不会返回任何结果。我可以用什么来实现这个目标?

1 个答案:

答案 0 :(得分:1)

我不是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
    }
}