Firebase in Swift nested query not working properly

后端 未结 2 719
梦谈多话
梦谈多话 2020-12-18 10:00

I have a JSON structure like the following:

{
  \"groups\" : {
    \"-KAv867tzVgIghmr15CM\" : {
      \"author\" : \"ruben\",
      \"name\" : \"Item A\"
            


        
2条回答
  •  执念已碎
    2020-12-18 10:22

    Frank's answer is on-point. I wanted to throw in an alternative that may or may not work for your situation as it requires a slight alteration to the database.

    groups
      gid_0
        author: "ruben"
        name:   "Item A"
        users
          uid_0: true
     gid_1
        author: "ruben"
        name:   "Item B"
        users
          uid_1: true
     gid_2
        author: "ruben"
        name:   "Item C"
        users
          uid_0: true
    

    And then some ObjC Code for a Deep Query

    Firebase *ref = [self.myRootRef childByAppendingPath:@"groups"];
    
    FQuery *query1 = [ref queryOrderedByChild:@"users/uid_0"];
    
    FQuery *query2 = [query1 queryEqualToValue:@"true"];
    
    [query2 observeSingleEventOfType:FEventTypeValue withBlock:^(FDataSnapshot *snapshot) {
        NSLog(@"key: %@   value: %@", snapshot.key, snapshot.value);
    }];
    

    This code does a deep query on the /groups for all groups that have a /users/uid_0 = true. In this case it returns gid_0 and gid_2

    It eliminates the need for iterations and multiple calls to the database.

    Adding a /users/ node to each group with a list of the uid's may offer some additional flexibility.

    Just a thought.

提交回复
热议问题