【问题标题】:How can I query multiple different sub collection at ones?如何查询多个不同的子集合?
【发布时间】:2020-09-21 08:18:22
【问题描述】:

最近我正在构建一个食谱应用程序。我使用 firebase 作为我的数据库。现在我想让用户找到我存储在我的食谱集合中的任何食谱。

每个 Food_Recipe 都有不同的子集合。我将用一个例子来解释我的问题。

现在,我想找到Recipe_name == Biiyani 的文件。 我可以使用这种方式轻松归档我的目标,

  Query query = FirebaseFirestore.getInstance().collection("Recipes").document("Food_Recipe")
            .collection("Rice_Recipe").orderBy("Recipe_name")
            .startAt(InputSearchText).endAt(InputSearchText +"\uf8ff");

但我需要在食谱集合中获得相同的结果。 比如Justimaging,如果Powder_Recipe也有Recipe_name Biiyani,那么不同子集合应该有2个结果。

【问题讨论】:

  • 请仅使用android-studio 标签来回答有关 Android Studio IDE 本身的问题。对于一般的 Android 编程问题,请使用android 标签。

标签: android firebase google-cloud-firestore


【解决方案1】:

如果您想查询多个具有不同名称的(子)集合,则必须对每个集合使用专用查询并合并结果。

如果您想避免这种情况,您需要调整您的数据模型。

我知道会有多个 Food_Recipe 文档,因为您写道“每个 Food_Recipe 都有不同的子集合”。

因此,例如,您可以在每个 Food_Recipe 文档下只有一个 subRecipes 子集合,并且在此子集合中,通过文档中的字段(例如一个名为 recipeType 的字段。这样就可以使用Collection Group query查询所有subRecipes子集合,如下:

Query query = FirebaseFirestore.getInstance().collectionGroup("subRecipes").orderBy("Recipe_name").startAt(InputSearchText).endAt(InputSearchText +"\uf8ff");

请注意,我将子集合称为 subRecipes,因为您已经有一个 Recipes 根集合。


如果您想获取Food_Recipe 文档的所有powder 配方,您可以过滤字段值,如下所示:

Query query = FirebaseFirestore.getInstance().collection("Recipes").document("Food_Recipe").collection("subRecipes").whereEqualTo("recipeType", "powder");

更具体地说,提出的数据模型如下

-- Recipes (root collection) 
   -- Food_Recipe_1 (document)
      -- subRecipes (subcollection)
         -- DocID#1 (document)
            - Recipe_Name: Biriyani (field)
            - recipeType: rice (field)             
            - ....  (field)     
         -- DocID#2 (document)
            - Recipe_Name: Peas Pulao (field)
            - recipeType: rice (field)             
            - .... (field)     
         -- DocID#3 (document)
            - Recipe_Name: Powder Recipe (field)
            - recipeType: powder (field)             
            - ....  (field)     
   -- Food_Recipe_2 (document)
      -- subRecipes (subcollection)
         -- DocID#4 (document)
            - Recipe_Name: Another Rice Recipe (field)
            - recipeType: rice (field)             
            - ....  (field)     
         -- DocID#5 (document)
            - Recipe_Name: Another Powder Recipe (field)
            - recipeType: powder (field)             
            - ....  (field)  

【讨论】:

  • 我使用了集合组查询,但它没有显示任何结果:(
  • 对不起,我的错误,我误解了你的问题。我要修改我的答案,给我 5 分钟。
  • 雷诺塔内克没问题。慢慢来。我会等。非常感谢。
  • 据我了解,如果有 Rice_Recipe、Powder_Recipe 和 Vegitable_Recipe 等子系列。我必须为这些每个子集合创建名为 Food_Recipe 的集合。并尝试收集组查询?
  • 我要试试这个,我会告诉你:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-11-16
  • 2017-10-09
  • 2013-09-06
  • 1970-01-01
  • 2020-08-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多