Fetching details of a group user belongs to in firebase

喜你入骨 提交于 2021-01-27 23:20:33

问题


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?


回答1:


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




回答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];
      }
    }
  }];


来源:https://stackoverflow.com/questions/46184206/fetching-details-of-a-group-user-belongs-to-in-firebase

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!