用户
-userId
-Name
-age
-groups
groupId1:true
groupId2:true
组
-groupId
-name
-desc
-UserId
-UserId1:true
-UserId2:true
以上是我在firebase中的数据库结构。我只登录了用户ID。 我想列出用户所属的所有组的详细信息。 我的方法是,
有没有更好的方法或建议?
答案 0 :(得分:1)
使用您当前的数据结构,您确实必须采用两步法:
这称为客户端加入,在Firebase中很常见。
或者,您可以复制每个用户组下每个组的最重要信息。 E.g。
UserGroups
User1
Group1: "This is the first group"
Group2: "This is the second group"
正如您在此示例中看到的,我们已将true
标记替换为组的实际名称。这样做的好处是,对于一个简单的用例,您只需阅读此列表而不进行客户端连接。缺点是您需要决定是否/如何保持数据同步。我在这里写了一个答案:How to write denormalized data in Firebase
请注意,您的数据模型并未完全展平,因为您正在混合实体类型。我建议从“用户所属的组列表”中拆分每个用户的元数据(其名称和描述)。这留下了四个顶级列表:
Users
Groups
UserGroups
GroupUsers
这是多对多关系的常见模式,我在此进一步描述:Many to Many relationship in Firebase
答案 1 :(得分:1)
以下方法将检索用户所属的组详细信息。
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];
}
}
}];