2014-06-18 33 views
0

的什么,我试图做一个例子里面过滤器:防止结膜标准声明

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

回答

1

我不是真的100%你正在尝试做什么。如果你只想要执行书查询,如果作者存在,可以使这样的事情...

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 
    } 
} 
+0

第二部分看起来像我想要的。你是在哪里找到那个东西的。 – mowwwalker

+0

我没有真正“找到”它的任何地方。我一直在与Grails合作7年或8年,并熟悉标准API。官方用户指南涵盖了很好的可能性。请参阅http://grails.org/doc/latest/guide/GORM.html#criteria。 –