异常动态过滤器 [英] anorm dynamic filters
问题描述
我正在研究一些 anorm 文档(来自 play 框架),并不清楚它是否支持常见的查询用例:动态过滤器,即用户在 10 个字段的搜索表单上填写 2 或 3 个搜索条件.
I'm studying a little the anorm documentation (from play framework) and is not clear if it supports a common query use case: dynamic filters, that is the user fills in 2 or 3 search criteria on a 10 fields search form.
在这种情况下,如何在没有经典字符串操作的情况下动态构造查询?
In this case how can I dynamically construct the query without the classic string manipulation?
推荐答案
是的,我认为 Robin Green 引用的问题包含了答案.只需使用占位符(例如 {criterion1}
)用所有可能的条件定义您的查询,并在查询上调用 on()
方法,传递实际的 Seq<接受的答案中描述的
Option
参数的/code>.
Yes, I think the question referenced by Robin Green contains the answer. Just define your query with all the possible criteria using placeholders (e.g. {criterion1}
) and call the on()
method on the query, passing the actual Seq
of Option
parameters as described in the accepted answer.
来自 Anorm 文档的修改示例,假设您有两个条件,但只希望您的查询过滤国家代码而不是首都:
Modified example from the Anorm doc, assuming you have two criteria but only want your query to filter on the country code and not on the capital:
SQL(
"""
select * from Country c
join CountryLanguage l on l.CountryCode = c.Code
where ({countryCode} is null or c.code = {countryCode})
and ({capital} is null or c.capital = {capital});
"""
).on("countryCode" -> Some("FRA"), "capital" -> None)
这应该可以解决问题.
这篇关于异常动态过滤器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!