【问题标题】:Grails retrieve custom query to Mapped ListGrails 将自定义查询检索到映射列表
【发布时间】:2013-09-29 13:46:08
【问题描述】:

我是 grails 的新手...

我想为我的 jquery 自动完成创建一个控制器

def arrSong = Song.executeQuery("select id, title as value, concat(artist, ' - ', title) as label from ${Song.name} where title like concat('%', :paramTitle, '%')", [paramTitle:params.term?.toString()])
render arrSong as JSON

通过这段代码我得到了这个 JSON:

[[1,"Mr. Brightside","The Killers - Mr. Brightside"]]

我的期望是这样的:

[{"id":1,"value":"Mr. Brightside","label":"The Killers - Mr. Brightside"}]

有人可以帮忙吗?

【问题讨论】:

  • 看看 ajaxdependancyselection 插件。它提供来自 gsp 的自动完成功能

标签: java grails


【解决方案1】:

executeQuery 你写的方式会返回一个未命名的结果列表,必须使用索引来检索。

例如:

[[1,"Mr. Brightside","The Killers - Mr. Brightside"]]

arrSong.each{println it[0]} 
//Prints 1, similarly it[1] for "Mr. Brightside" and so on

您需要的是一个map 表示您的结果集,如下所示,那么您应该能够毫不费力地将地图呈现为 JSON。

def query = """
             select new map(id as id, 
                            title as value, 
                            concat(artist, ' - ', title) as label) 
             from ${Song.name} 
             where title like concat('%', :paramTitle, '%')
            """

def arrSong = Song.executeQuery(query, [paramTitle: params.term?.toString()])

render arrSong as JSON

应该返回

[{"id":1,"value":"Mr. Brightside","label":"The Killers - Mr. Brightside"}]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-09-22
    • 1970-01-01
    • 2017-10-16
    • 1970-01-01
    • 2020-08-17
    • 2014-08-26
    • 1970-01-01
    相关资源
    最近更新 更多