【问题标题】:Grails using query in g:select with serviceGrails 在 g:select 和服务中使用查询
【发布时间】:2012-12-27 21:06:46
【问题描述】:

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

查看sn-p:

<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,但我无法让它工作。

谢谢!

【问题讨论】:

  • 只是一个公共服务公告:使用 groovy sql 违背了数据库独立性的目的。使用 HQL 或对象本身。

标签: grails groovy grails-orm


【解决方案1】:

您的 populatePrompts 函数没有返回有意义的值。如果您使用collectMany 而不是each 进行迭代,则表达式的值将是您查询的所有结果的串联。试试这样的:

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

您可能还希望在结果上调用 unique 以避免在您的 g:select 输入中重复。

【讨论】:

  • 是的!太感谢了,就这样搞定了。现在还有一个问题。它返回一个地图列表。有什么方法可以只提取值而不是键?
  • 在列表成员(例如listPromptValues = populatePrompts(reportInstance)*.values())上调用values(),您将获得列表列表。如果您选择单个列,请flatten() 它,您将获得一个平面列表的结果。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-05-13
  • 1970-01-01
  • 1970-01-01
  • 2012-09-12
  • 1970-01-01
  • 1970-01-01
  • 2022-09-14
相关资源
最近更新 更多