grails find objects by many parameters
I have rather big form where a user can choose any number of parameters (from 1 to 10).
Example:
- Cities - NYC, LA ; age - 18
- Cities - null (nothing was chosen) ; age - 23, 57
How should I implement a find method at the GORM level (bad way - method that composes query string, add params if not null, etc)?
Then I should search in my database for app开发者_高级运维ropriate objects. Another limitation - should use executeQuery?
**[EDITED]*** I remembered that i didn`t post my own answer. There it is:
def resultList = Organization.createCriteria().list(max: params.max, offset: params.offset) {
and {
if (params.chosenNomenc != null) {
nomenclatures {
ilike("title", params.chosenNomenc)//for string
}
}
if (params.chosenCountries != null) {
countries {
'in'("title", params.chosenCountries)//for list
}
}
cache true
order("id", "asc")
}
}
println("resultList:" + resultList)
[organizationList: resultList, total: resultList.totalCount, params: params]
}
Regards, Dmitry.
Using Criteria in the controller is the best way.
def locProps = Location.metaClass.properties*.name
def locs = Location.withCriteria {
and {
params.each { field, value ->
if (locProps.grep(field) && value) {
// more checks here
Use the Criteria API and in it's closure you can use conditional statements (if/else) to build it based on the presence of params.
Assuming your <select> tags are named ages
and cities
and you have a Person domain with String properties age
and city
:
Person.withCriteria {
if (params.list('ages')) { // inList('fieldName', null) causes an error
inList 'age', params.list('ages')
}
if (params.list('cities')) {
inList 'city', params.list('cities')
}
}
I suggest you to user createCriteria
or withCriteria
only.
Lets take an example:
If the parameters to the action are as u had given:
1) Cities - NYC, LA ; age - 18
2)Cities - null(nothing was chosen) ; age - 23, 57
And suppose your domain class is User
then:
def result = User.withCriteria (max: params.max){
if (params.Cities)
eq('city', params.Cities)
if (params.age)
eq('age', params.age)
}
It will return list of the matching objects of domain class User
.
For more details, Please take a look at createCriteria
or withCriteria
in Grails documentation.
精彩评论