3

有没有办法用通配符自动包装所有搜索?

例如:

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

1 回答 1

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    
于 2013-03-13T20:03:33.810 回答