Claus Menke
Claus Menke

Reputation: 35

firebase - get all chat rooms for a member

I'm integrating multi-room chat in my app and I'm stuck with getting a list of all chat room a specific user is member of.

The structure looks like this:

members structure

The rooms and members are created with childByAutoId like this:

FIRUser *user = [FIRAuth auth].currentUser;  
mdata[@"uid"] = user.uid;

roomKey = [[_rootRef child:@"messages"] childByAutoId].key;

NSString *memberID = [[[_rootRef child:@"members"] child: roomKey ] child: user.uid ].key;

// set Meta data for member to be able to recognize later

[[[[_rootRef child:@"members"] child: roomKey ] child: memberID ] setValue:mdata];

Now I'm trying the get the list of rooms for a (hard coded) user like that:

-(void) getRoomKeys {

    [[[[_rootRef child: @"members"] queryOrderedByChild:@"uid" ] queryEqualToValue:@"QLfRoGpoCjWpzira7fljBj8g3EJ3"]
     observeEventType:FIRDataEventTypeValue withBlock:^(FIRDataSnapshot *snapshot) {
         NSDictionary<NSString *, NSString *> *message = snapshot.value;
     }];
  }

This return 0 key/value pairs.

When I take out the query I get all room keys. When I change the structure to this uid one level higher

I will get all rooms for that user but with this structure I can't add other members to that room. So I need to dig one level deeper.

So how to set the query for nodes that have been created by childByAutoId?

Thanks for your help!

Upvotes: 1

Views: 1858

Answers (1)

Callam
Callam

Reputation: 11539

Try considering this data structure.

{
    "rooms": {
        "-KQgDxLIt88yPt6nacDu": { ... }
    },
    "members": {
        "QLfRoGpoCjWpzira7fljBj8g3EJ3": { ... }
    },
    "member-rooms": {
        "QLfRoGpoCjWpzira7fljBj8g3EJ3": {
            "-KQgDxLIt88yPt6nacDu": true
        }
    }
}

You can retrieve the keys of the rooms a member is part of by observing member-rooms/{uid}:

[[_rootRef child: @"member-rooms/QLfRoGpoCjWpzira7fljBj8g3EJ3"] observeEventType:FIRDataEventTypeValue withBlock:^(FIRDataSnapshot *snapshot) {
     NSLog("%@", snapshot.value); // the keys of the rooms of the member
}];

Upvotes: 3

Related Questions