Slick 3 dynamic groupby - fields from its List[String]

亡梦爱人 提交于 2019-12-08 05:02:34

问题


Lets say i want to execute the query:

select columnName1,columnName2,Sum(*)
from table
group by columnName1,columnName2

where columnName1,columnName2 is supplied from list[string] ("columnName1",columnName2")

how can i do it with slick? if the columns are known by compile time, i can easily use the groupBy function:

tableQuery.groupBy { r => (r.columnName1,r.columnName2)}.map (case groupName,group) => (groupName._1,groupName._2,group.map(...).avg)}

but what about dynamic?


回答1:


You can use the r.column("foo") syntax to access columns dynamically at runtime, so I believe you can just do something like the following?

columnNames = List("col1", "col2")
tableQuery
    .groupBy(r => columnNames.map(name => r.column(name)))
    .map({ case (groupName, group) => /* do something with it */})



回答2:


To convert a string column name to Rep type, you can use the Slick AST Library. I had a similar requirement and done it using the AST Library. You can refer to this code, which does the same thing. I also followed the same code to solve my requirement.



来源:https://stackoverflow.com/questions/34705546/slick-3-dynamic-groupby-fields-from-its-liststring

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!