2013-03-13 41 views
3

有沒有辦法用通配符自動包裝所有搜索?Grails插件可搜索 - 默認通配符搜索

例如爲:

Book.search("*${params.q}*", params) 
+0

你能嘗試在urlMapping中(HTTP ://grails.org/doc/latest/guide/single.html#urlmappings)使用任意變量? – 2013-03-14 18:13:48

回答

2

我不熟悉.search(您正在使用的插件嗎?)。但是,對於模型中的通配符搜索,我通常會在域模型類中創建一個方法。在你的榜樣,

在Book模型類:

class Book { 
    String title 
    String author 
    int year 

    static List wildSearch(par, val) { 
     def foundList = this.executeQuery("select b FROM Book b WHERE ${par} like \'%${val}%\'") 
     return foundList 
    } 
} 

在你的控制器:

def searchBook = { 
    def b1 = new Book(title: "Farewell To Arms", author: "Ernest Hemingway").save() 
    def b2 = new Book(title: "The Brother's Karamazov", author: "Anton Chekov").save() 
    def b3 = new Book(title: "Brothers in Arms", author: "Cherry Dalton").save() 

    // If you search for "Arms", This returns b1 and b3 
    def found = Book.wildSearch("title", params.title) 
} 

實例網址:

http://localhost:8080/mytest/mycontroller/searchBooks?title=Arms  
+0

Searchable是一個Grails插件,使搜索更容易一些。感謝您的建議,但我想知道是否有方法來默認插件。 – Nix 2013-03-14 13:13:56

+0

應該更仔細地閱讀您的問題標題。對於那個很抱歉。 – ibaralf 2013-03-14 17:04:08