2

Below is my database structure in firebase. I only have signed-in users Id.

User

-userId

    -Name
    -age
    -groups

        groupId1:true
        groupId2:true

Group

-groupId

    -name
    -desc
    -UserId

        -UserId1:true
        -UserId2:true

I want to list the details of all the groups that user belongs to. My approach is,

  1. Find all the groups my user belongs to by checking the index from User.
  2. Using the list of groupid we got from step1, get details of group from Groups.

Is there any other better suggestions?

Lilac
  • 580
  • 1
  • 7
  • 25
django
  • 190
  • 14

2 Answers2

2

With your current data structure you will indeed have to do the two-stepped approach:

  1. Load the list of group IDs
  2. Load the metadata (e.g. name) of each group

This is known as a client-side join and is quite common with Firebase.

Alternatively you can duplicate the most important information about each group under each user's groups. E.g.

UserGroups
  User1
    Group1: "This is the first group"
    Group2: "This is the second group"

As you see in this sample we've replace the true marker with the actual name of the group. The advantage of this is that for a simple use-case you only have to read this list and not do a client-side join. A disadvantage is that you need to decide whether/how to keep the data sync. I wrote an answer with the option for that here: How to write denormalized data in Firebase

Note that your data model is not fully flattened, since you're mixing entity types. I recommend splitting the metadata of each user (their name and description) from the "list of groups that the user belongs to". That leaves you with four top-level lists:

Users
Groups
UserGroups
GroupUsers

This is a common pattern for many-to-many relations, which I further described here: Many to Many relationship in Firebase

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
  • As my application needs to update the group info everytime it changes, i prefer to go with the first approach of doing a 2 step retrieval. – django Sep 13 '17 at 15:35
  • I have faced a showstopper by doing the above approach.Could anyone please give any advice on this issue https://stackoverflow.com/questions/46204767/accessing-array-in-component-from-ionic-view – django Sep 13 '17 at 19:06
2

Below method will retrieve the Group details which user belongs to.

self.usersPerGroupRef = [_rootRef child:@"Group"];
  [_usersPerGroupRef observeSingleEventOfType:FIRDataEventTypeValue withBlock:^(FIRDataSnapshot * _Nonnull snapshot) {
    self.usersArray = [NSMutableArray new];
    for (snapshot in snapshot.children) {
      NSMutableDictionary *groupDict = [NSMutableDictionary new];
      groupDict = snapshot.value[@"UserId"];
      if ([groupDict objectForKey:@"userID"]) { 
       NSLog(@"Group Name: %@",snapshot.value[@"name"]);
        [self.usersArray addObject:snapshot.key];
      }
    }
  }];
user3310076
  • 133
  • 12