ibaralf
ibaralf

Reputation: 12518

Grails search list with 'like'

So I have domain classes

class SalesRep {
   SalesTerritory territory
}
class SalesTerritory {
   hasMany=[accounts: AccountCustomer]
   String territoryCode
}

class AccountCustomer {
   String accountName
   String accountCode
   belongsTo = SalesTerritory
   hasMany=[salesTerritories: SalesTerritory]
}

In the controller, I can get the accounts by:

def salesRep = SalesRep.findBy... // 
def accounts = salesRep.territory.accounts

I would like to do two things:

1) Search for accounts with some string (ex. '%My Account%'), something like below:

def accounts = salesRep.territory.accounts.find("accountName like '%My Account%'")

2) Sort accounts

def accounts = salesRep.territory.accounts.sort("accountName")

I know I can add static mapping = { sort accountName } in the domain class, but what if I want to sort using a different field such as accountCode. Thanks, I tried using createCriteria, but couldn't get it to work.

Thanks.

Upvotes: 0

Views: 5914

Answers (2)

ibaralf
ibaralf

Reputation: 12518

Thanks for the answer. I couldn't get that to work but one solution I got to work is below, basically using regular expressions.

def myAccount = "My Account"
accounts = salesRep.territory.accounts.findAll {
   it.accountName ==~ /(?i).*${myAccount}.*/
}

The (?i) makes the match ignore case.

Upvotes: 2

Universitas
Universitas

Reputation: 493

Try

def accounts = salesRep.territory.accounts.findAllByAccountNameLike("%${MyAccount}%")

Like is case sensitive, but if you want to ignore case, then use iLike.

For sorting you can use

def accounts = salesRep.territory.accounts.list(sort:'accountName', order:'asc')

You can also define sorting in your domain class via static mapping

static mapping = {
     sort accountName:"asc"
}  

But I think if you want to sort the way you have it you need to add a comparator and make sure your class implements Comparable.

class YourClassName implements Comparable{

 String accountName
 ...


 @Override
 public int compareTo(Object o) {
     if (o == null || this == null) {
         return 0;
     } else {
         return value.compareTo(o.value)
     }
 }
}

Then when you call .sort it will use the compareTo method in your domain.

Upvotes: 1

Related Questions