Cloud Firestore通过引用从另一个集合中获取集合 [英] Cloud Firestore get collection by reference from another collection

查看:42
本文介绍了Cloud Firestore通过引用从另一个集合中获取集合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为 Products 的集合,还有一个名为 Category 的集合.

I have a collection called Products and another one named Category.

产品文档的字段 idCategory 引用类别的ID.

Products document has a field idCategory, referencing category's id.

我想从类别名称等于"Soda"的 Products 中获取所有文档.

I want to get all documents from Products where the category name is equals "Soda".

我该怎么做?

推荐答案

我想从类别名称等于"Soda"的产品中获取所有文档.

I want to get all documents from Products where the category name is equals "Soda".

因为在单个文档中没有所有数据,所以需要两次查询数据库.一旦获得该类别的ID(在这种情况下为"Soda"),然后根据该ID获得相应的产品.这是因为Firestore不支持跨多个集合的查询.单个查询只能使用单个集合中的文档属性.

Because you don't have all data in a single document, you need to query your database twice. Once to get the id of the category which is "Soda" in this case and then based on that id get the corresponding products. This is because Firestore doesn't support queries across multiple collections. A single query may only use properties of documents in a single collection.

为什么要查询数据库两次,所以一次查询并获得所需文档的成本也很高.为此,您需要对数据库架构进行一些更改.由于单个产品可能属于多个类别,因此您的新架构应如下所示:

By why to query the database twice, which is aslo costly when you can query once and get the desired documents. For that, you need to make a little change in your database schema. Since a single product may belong to multiple categories, your new schema should look like this:

Firestore-root
    |
    --- products (collection)
          |
          --- productId (document)
                |
                --- productName: "Soda Water"
                |
                --- category: ["Soda", "Other Category"]
                |
                --- //Other properties

要获取除 Soda 类别以外的所有文档,请使用以下代码行:

To get all document that are apart of Soda category, please use the following lines of code:

FirebaseFirestore rootRef = FirebaseFirestore.getInstance();
CollectionReference productsRef = rootRef.collection("products");
Query query = productsRef.whereArrayContains("category", "Soda");

您还可以保留引用而不是仅保留ID,为此,请从此

You can also hold references instead of only ids but for that, please see my answer from this post.

这篇关于Cloud Firestore通过引用从另一个集合中获取集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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