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