2012-12-27 25 views
0

Grails模型相當新穎,並且在我的數據庫事務中使用服務時遇到了一些麻煩。使用g中的查詢的Grails:選擇服務

服務:

class ReportService { 

    def dataSource 
    def listDatatypeValues(Datatype dt) { 
     def sql = new Sql(dataSource) 
     def list = sql.rows (dt.statement) 
     return list 
    } 
} 

控制器:

def run(Long id) { 

    def reportInstance = Report.get(id) 
    def listPromptValues = populatePrompts(reportInstance) 

    if (!reportInstance) { 
     flash.message = message(code: 'default.not.found.message', args: [message(code: 'report.label', default: 'Report'), id])    
     return 
    } 
    [reportInstance: reportInstance, listPromptValues: listPromptValues] 
} 

def populatePrompts(Report rp){ 
    //for a prompt in the report, go out and get it's values 
    rp.prompts.each { 
     List list = reportService.listDatatypeValues(it.datatype) 
    } 
} 

查看片段:

<g:if test="${reportInstance?.prompts}"> 
    <li class="fieldcontain"> 
    <g:each var="prompt" in="${reportInstance.prompts}"> 
    <g:if test="${prompt.datatype.type == 'DropDown'}"> 
    <g:select id="prompt.name" from="${listPromptValues}" name="prompt.name" value="" noSelection="['':'']"/> 
     </g:if> 
    </g:each> 
    </li> 
</g:if> 

我們有一個報表對象,包含提示,又包含一個數據類型。對於任何給定的報告,當它在UI上拉起時,它會給出報告詳細信息,然後列出提示值的提示值。問題是當前的設置將對象引用列爲提示值,而不是從服務返回的值列表。

舉例如下:報告1有2個提示:開始期限代碼和結束期限代碼。它們都使用術語代碼作爲數據類型,因爲它是相同的SQL查詢,並且從listDataTypeValues返回的列表將是存儲在數據庫中的70+術語代碼的列表。

任何想法或方向?

我試着跟着this以下,但我無法得到它的工作。

謝謝!

+1

只是一個公共服務公告:使用groovy sql打敗了數據庫獨立的目的。使用HQL或對象本身。 –

回答

1

您的populatePrompts函數沒有返回有意義的值。如果用collectMany而不是each進行迭代,則表達式的值將是來自查詢的所有結果的串聯。嘗試是這樣的:

def populatePrompts(Report rp){ 
    rp.prompts.collectMany { 
     reportService.listDatatypeValues(it.datatype) 
    } //.unique() 
} 

您可能還需要調用獨特的結果,以避免在您g:select輸入重複。

+0

是的!非常感謝你,那樣做。現在還有一個問題。它返回一張地圖列表。任何方式拉只是值,而不是關鍵? – idonaldson

+0

在列表成員(例如'listPromptValues = populatePrompts(reportInstance)*。values()')上調用'values()',您將得到一個列表列表。如果你選擇了一個單獨的列,將其平坦化,你就可以得到結果列表。 – ataylor