Firestore:多个条件 where 子句 [英] Firestore: Multiple conditional where clauses

查看:61
本文介绍了Firestore:多个条件 where 子句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,我的图书列表有动态过滤器,我可以在其中设置特定的颜色、作者和类别.此过滤器可以一次设置多种颜色和多个类别.

For example I have dynamic filter for my list of books where I can set specific color, authors and categories. This filter can set multiple colors at once and multiple categories.

   Book > Red, Blue > Adventure, Detective.

如何有条件地添加where"?

How can I add "where" conditionally?

  firebase
    .firestore()
    .collection("book")
    .where("category", "==", )
    .where("color", "==", )
    .where("author", "==", )

    .orderBy("date")
    .get()
    .then(querySnapshot => {...

推荐答案

正如您在 API 文档中所见,collection() 方法返回一个 CollectionReference.CollectionReference 扩展了 Query,并且 Query 对象是不可变的.Query.where()Query.orderBy() 返回添加操作的新 Query 对象在原始查询(保持不变)之上.您将不得不编写代码来记住这些新的 Query 对象,以便您可以继续与它们链接调用.所以,你可以像这样重写你的代码:

As you can see in the API docs, the collection() method returns a CollectionReference. CollectionReference extends Query, and Query objects are immutable. Query.where() and Query.orderBy() return new Query objects that add operations on top of the original Query (which remains unmodified). You will have to write code to remember these new Query objects so you can continue to chain calls with them. So, you can rewrite your code like this:

var query = firebase.firestore().collection("book")
query = query.where(...)
query = query.where(...)
query = query.where(...)
query = query.orderBy(...)
query.get().then(...)

现在您可以输入条件来确定要在每个阶段应用哪些过滤器.只需为每个新添加的过滤器重新分配 query.

Now you can put in conditionals to figure out which filters you want to apply at each stage. Just reassign query with each newly added filter.

if (some_condition) {
    query = query.where(...)
}

这篇关于Firestore:多个条件 where 子句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆