英文:
How to add a filter to a datastore query based on condition
问题
我正在从一个POST请求中接收参数,并根据这些参数的存在与否来修改数据存储查询。以下是一个示例,我们可能会从POST消息中接收到一个名为"title"的变量。如果存在该变量,我希望将其包含在查询中作为一个过滤条件:
q := datastore.NewQuery("book").
Filter("author =", "DB").
if title != nil {Filter("title =", title).}
Order("author")
有什么建议吗?
英文:
I am receiving parameters from a POST and based on if those parameters exist I want to alter the datastore query. Here is an example where we may or may not receive a "title" variable from the post message. If it does exist, I want to include it in the query as a filter:
q := datastore.NewQuery("book").
Filter("author =", "DB").
if title != nil {Filter("title =",title).}
Order("author")
Any suggestions?
答案1
得分: 1
可选地,在查询中调用另一个Query.Filter()
方法,如果参数存在的话。只需确保将返回值存储起来,因为它可能是一个不同的派生查询。
原因是所有的查询构建器/修改器方法都返回一个派生查询,你可以使用它来链接多个操作。你不必一次完成所有操作,你可以存储中间结果查询,并从那里继续“工作”(例如添加新的过滤器)。只需记住始终存储返回值,并且必须使用最后一个方法返回的Query
。
解决方案(候选):
q := datastore.NewQuery("book").Filter("author =", "DB")
if title != nil {
q = q.Filter("title =", title)
}
q = q.Order("author")
注意:
你没有提到它,但我假设title
是一个string
。string
类型的变量不能有nil
值。string
的零值是空字符串""
,所以用它来进行比较/测试:
q := datastore.NewQuery("book").Filter("author =", "DB")
if title != "" {
q = q.Filter("title =", title)
}
q = q.Order("author")
英文:
Optionally call another Query.Filter()
method on the query if the parameter exists. Just be sure you store the return value as it may be a different, derived query.
The reason is that all query builder/modifier methods return a derived query which you can use to chain multiple operations. You don't have to do it all in one step though, you can store the intermediate result query and continue the "work" from there (e.g. add new filters). Just remember to always store the return values, and you have to use the Query
returned by the last method.
Solution (candidate):
q := datastore.NewQuery("book").Filter("author =", "DB")
if title != nil {
q = q.Filter("title =", title)
}
q = q.Order("author")
Note:
You did not mention it, but I assume title
is a string
. Variables of type string
cannot have a nil
value. The zero value of a string
is the empty string ""
so use that to compare/test:
q := datastore.NewQuery("book").Filter("author =", "DB")
if title != "" {
q = q.Filter("title =", title)
}
q = q.Order("author")
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论