简体   繁体   中英

Grails Plugin Searchable - default wildcard search

Is there a way to automatically wrap all searches with a wildcard?

eg:

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

I'm not familiar with .search (are you using a plugin?). However, for a wildcard search in models, I typically create a method inside the domain model class. In your example,

In the Book model class:

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

In your controller:

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)
}

Example URL:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM