2012-06-26 9 views
1

我是grails新手,但以前使用.net與c#和linq查詢數據庫的經驗。grails - 在查詢中使用動態列表

我想通過使用多選選項下拉框的可選項來過濾對象列表。所以對於控制器,我會得到一個參數列表,其中一些參數將爲空。所以我想要有類似於
DailyProduction.Where(x => loaction.contains(x.location)).Select().ToList()的東西。

但是,它在groovy和grails中看起來並不那麼簡單。

這裏是我試過:

def filteredList = DailyProductionReport.createCriteria() 
    def results = filteredList.list { 

     if(params.locationSelect != null) 
      'in'("location", [params.locationSelect.each{ it != null}]) 

    } 

,但我得到一個運行時異常,說:

Class: 
java.lang.ClassCastException 
Message: 
[Ljava.lang.String; cannot be cast to java.lang.String 

我已經試過過目有任何運氣不同的論壇。我幾乎在我的智慧結束。如果任何時髦的大師能夠爲我闡明一些事情,我將不勝感激。

感謝

回答

2

它看起來像你的問題可能是

[params.locationSelect.each{ it != null }] 

each用於迭代和結果表達式僅僅是列表上迭代。另外,方括號將該列表嵌套在另一個列表中。你可能想

'in'('location', params.locationSelect.findAll { it != null }) 

在這種特殊情況下,你也可以只使用身份關閉,因爲"groovy truth"的對象是相同的測試空:

'in'('location', params.locationSelect.findAll()) 
+0

呸......太慢;-) –

+0

非常感謝。並感謝有用的解釋。這真的有訣竅。 – TroyB