How can I query multiple different sub collection at ones?

前端 未结 1 665
悲哀的现实
悲哀的现实 2021-01-27 13:29

Recently I am building a recipe app. I am using firebase as my database. Now I want to let the users to find any recipe which I have stored in my recipe Collection.

Each

1条回答
  •  悲哀的现实
    2021-01-27 14:05

    If you want to query several (sub)collections with different names, you will have to use a dedicated query for each of those collections and merge the results.

    If you want to avoid that you would need to adapt your data model.

    I understand that there are going to be several Food_Recipe documents, since you wrote that "Each Food_Recipe has different subcollections".

    So, for example, you could have only one subRecipes subcollection under each Food_Recipe document and, in this subcollection, make the difference between the powder and rice recipes with a field in the document (e.g. a field named recipeType). This way you can use a Collection Group query to query all the subRecipes subcollections, as follows:

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

    Note that I called the subcollections subRecipes, since you already have a Recipes root collection.


    And if you want to get all the powder recipes for the Food_Recipe document, you filter on the field value, as follows:

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

    More concretely, the proposed data model is the following

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

    0 讨论(0)
提交回复
热议问题