我想检查一下我是否正确索引了我的关系数据,因为我想把头放在Firebase上。我在用户和地址之间有两种联系,两者都是一对一的关系。想法是,最初仅用电子邮件创建用户节点,然后在添加地址时,将addressID的密钥添加到用户节点,同时将userID的密钥添加到地址节点。这意味着类似于Firebsae文档的“结构数据”部分(底部)中的建议。但是,为了标识用户节点内的地址并标识地址节点内的用户,我使用了它们的自动生成的密钥(例如,前者为address:userAutoID,user:addressAutoID;而不是userAutoID:true和addressAutoID:true;更具描述性,更易于理解。使用自动生成的ID作为键并不表示该键代表什么)。 JSON结构如下(两个节点都是最高节点的子节点):
如您所见,地址拥有用户的ID,而用户拥有地址ID。我觉得我用来实现此目的的代码似乎很长,我可能会以错误的方式进行操作。当用户填写地址表格并按下提交时,将触发代码。因此,用户节点位于地址节点之前。我使用for循环依次获取每个存在的地址的密钥,然后将其馈入另一个查询,该查询将查找当前地址节点中是否存在当前用户的ID作为userID密钥的值。如果是这样,那么我将当前地址的ID设置为当前用户关联节点内的addressID的值。这是代码:
self.rootRef.child("Addresses").observeSingleEvent(of: .value, with: { snapshot in
for address in snapshot.children {
guard let addressSnapshot = address as? FIRDataSnapshot else {
print("failed to get addressSnapshot")
return
}
let addressSnapshotKey = addressSnapshot.key
self.rootRef.child("Addresses").child(addressSnapshotKey).observeSingleEvent(of: .value, with: { snapshot in
guard let snapshotValue = snapshot.value as? [String: AnyObject] else {
print("error getting snapshotValue")
return
}
let userID = FIRAuth.auth()?.currentUser?.uid
if (snapshotValue["userID"] as! String) == userID {
let correctKey = addressSnapshotKey
let userRef = self.rootRef.child("Users").child(userID!)
userRef.child("addressID").setValue(correctKey)
}
})
}
})
我可以看到,当“用户和地址”节点很大时,从一段代码运行两个查询可能会变得很昂贵。任何反馈将不胜感激!
最佳答案
我还将重用自动生成的用户密钥作为“地址”下的密钥。
- Users
- xyz (auto generated)
- email: jo@jo.com
- Addresses
- xyz (use the previously created id here too)
- street
- author
- lat
- lon
关于swift - 在Firebase Swift中正确索引关系数据,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/40952488/