Querying in Firebase by child of child

前端 未结 2 1590
情深已故
情深已故 2021-01-07 07:34

I have a structure of objects in Firebase looking like this:

-KBP27k4iOTT2m873xSE
    categories
        Geography: true
        Oceania: true
    correctans         


        
2条回答
  •  迷失自我
    2021-01-07 07:53

    Adding some additional code to Tim's answer for future reference.

    Just use a deep query. The parent object key is not what is queried so it's 'ignored'. It doesn't matter whether it's a key generated by autoId or a dinosaur name - the query is on the child objects and the parent (key) is returned in snapshot.key.

    Based on your Firebase structure, this will retrieve each child nodes where Oceania is true, one at a time:

          let questionsRef = Firebase(url:"https://baseurl/questions")
          questionsRef.queryOrderedByChild("categories/Oceania").queryEqualToValue(true)
                .observeEventType(.ChildAdded, withBlock: { snapshot in
                   print(snapshot)
            })
    

    Edit: A question came up about loading all of the values at once (.value) instead of one at at time (.childAdded)

          let questionsRef = Firebase(url:"https://baseurl/questions")
          questionsRef.queryOrderedByChild("categories/Oceania").queryEqualToValue(true)
                  .observeSingleEventOfType(.Value, withBlock: { snapshot in
                  print(snapshot)
           })
    

    Results in (my Firebase structure is a little different but you get the idea) uid_1 did not have Oceania = true so it was omitted from the query results.

    Snap (users) {
        "uid_0" =     {
            categories =         {
                Oceania = 1;
            };
            email = "dude@thing.com";
            "first_name" = Bill;
        };
        "uid_2" =     {
            categories =         {
                Oceania = 1;
            };
            "first_name" = Peter;
        };
    }
    

提交回复
热议问题