2014-06-18 35 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。 –