Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/363.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java Cloud Firestore通过引用从另一个集合获取集合_Java_Android_Firebase_Google Cloud Firestore - Fatal编程技术网

Java Cloud Firestore通过引用从另一个集合获取集合

Java Cloud Firestore通过引用从另一个集合获取集合,java,android,firebase,google-cloud-firestore,Java,Android,Firebase,Google Cloud Firestore,我有一个名为Products的集合和另一个名为Category的集合 产品文档有一个字段idCategory,引用类别的id 我想从类别名称等于Soda的产品中获取所有文档 我该怎么做呢?看起来您需要做一个简单的查询: 我想从类别名称等于Soda的产品中获取所有文档 因为在一个文档中没有所有数据,所以需要查询数据库两次。在本例中,一次获取苏打水类别的id,然后根据该id获取相应的产品。这是因为Firestore不支持跨多个集合的查询。单个查询只能使用单个集合中文档的属性 为什么要查询两次数据库,

我有一个名为Products的集合和另一个名为Category的集合

产品文档有一个字段idCategory,引用类别的id

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


我该怎么做呢?

看起来您需要做一个简单的查询:

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

因为在一个文档中没有所有数据,所以需要查询数据库两次。在本例中,一次获取苏打水类别的id,然后根据该id获取相应的产品。这是因为Firestore不支持跨多个集合的查询。单个查询只能使用单个集合中文档的属性

为什么要查询两次数据库,如果只需查询一次就可以得到所需的文档,那么成本也会很高。为此,您需要对数据库模式进行一些更改。由于单个产品可能属于多个类别,因此您的新模式应如下所示:

Firestore-root
    |
    --- products (collection)
          |
          --- productId (document)
                |
                --- productName: "Soda Water"
                |
                --- category: ["Soda", "Other Category"]
                |
                --- //Other properties
要获取Soda类别之外的所有文档,请使用以下代码行:

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

编辑:您也可以保留引用,而不仅仅是id,但为此,请查看我的答案。

不可能,因为Soda不是CategoryAh的id属性!我想我误解了您的nosql结构。我很高兴你找到了解决办法。亚历克斯很好地解释了你的结构。您的声明我想从类别名称等于Soda的产品中获取所有文档。表示Soda是产品文档的一部分,变量名为category。不幸的是,在这种情况下无法更改数据库:/n在这种情况下,您应该查询数据库两次。但请记住,在Firestore中,一切都与读写次数有关。请参阅更多信息。因此,你的应用程序将花费比需要更多的读取操作,这将花费你更多。如果这是一个愚蠢的问题,我很抱歉,但是,当我使用.collection“Category”.document“Soda”.collection“Products”?你正在查找产品子集合中的所有文档。
FirebaseFirestore rootRef = FirebaseFirestore.getInstance();
CollectionReference productsRef = rootRef.collection("products");
Query query = productsRef.whereArrayContains("category", "Soda");