2011-03-04 12 views
1

我有一個比較大的形式,用戶可以選擇任意數量的參數(從1到10)。grails通過很多參數找到對象

實施例:

  1. 城市 - NYC,LA;年齡 - 18
  2. 城市 - null(沒有被選中);年齡 - 23,57

我應該如何在GORM級別實現一個find方法(壞方法 - 組成查詢字符串的方法,如果不爲空,則添加params等)?

然後,我應該在我的數據庫中搜索適當的對象。另一個限制 - 應該使用executeQuery

** 將帖子 ** * 我記得我didn`t發表我自己的答案。它是:

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

問候,德米特里。

回答

4

在控制器中使用Criteria是最好的方法。

def locProps = Location.metaClass.properties*.name 
    def locs = Location.withCriteria { 
     and { 
      params.each { field, value -> 
       if (locProps.grep(field) && value) { 

        // more checks here 
+0

已經給出了同樣的答案。 – Gregg 2011-03-05 21:59:23

+2

誠然,並不是想竊取你的雷霆。有時候只是馬上看到一個實際的例子。 – snowmanjack 2011-03-07 21:42:33

1

使用Criteria API並在它的閉包中,您可以使用條件語句(if/else)基於params的存在來構建它。

-1

假設你<選擇>標籤被命名爲agescities,你有一個人與域名字符串性質agecity

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

我建議你到用戶createCriteria或僅withCriteria
我們舉個例子:
如果這個動作的參數是你給出的:
1)Cities - NYC,LA;年齡 - 18
2)城市 - null(沒有選擇任何東西);年齡 - 23,57

而且假設你的域類是User則:

def result = User.withCriteria (max: params.max){ 
    if (params.Cities) 
     eq('city', params.Cities) 
    if (params.age) 
     eq('age', params.age) 
} 

它將返回域類User的匹配對象的列表。
有關更多詳細信息,請參閱Grails文檔中的createCriteriawithCriteria

+0

已經給出了同樣的答案。 – Gregg 2011-03-05 21:59:47