firebase数据结构是
{
"eventAttendees" : {
"fm" : {
"1" : "David",
"2" : "Alice"
}
},
"events" : {
"fm" : {
"date" : "2017-06-16",
"name" : "Firebase Meetup"
},
"gm" : {
"date" : "2017-08-12",
"name" : "Meet Linh"
}
},
"users" : {
"1" : {
"email" : "david@gmail.com",
"name" : "David"
},
"2" : {
"email" : "alice@gmail.com",
"name" : "Alice"
},
"10" : {
"email" : "khanh@gmail.com",
"name" : "Khanh"
}
}
}
我想找到所有转到fm活动的用户。这是我的代码:
let ref = Database.database().reference()
ref.child("eventAttendees/fm").observe(.value, with: { (snapshot) in
print (snapshot.key)
ref.child("users/\(snapshot.key)").observeSingleEvent(of: .value, with: { (userSnapshot) in
let content = userSnapshot.value as? [String : AnyObject] ?? [:]
print(content)
})
})
我按照本教程https://youtu.be/Idu9EJPSxiY?t=3m14s,
根据教程snapshot.key
,应返回“1”,“2”,以便ref.child("users/\(snapshot.key)")
为ref.child("users/1")
但在我的代码中,snapshot.key
返回“fm”和ref.child("users/\(snapshot.key)")
将为ref.child("users/fm")
我的代码中的问题在哪里?
答案 0 :(得分:3)
在eventAttendees/fm
下,您有多个孩子。因此,您还需要在代码中循环遍历这些子节点:
let ref = Database.database().reference()
ref.child("eventAttendees/fm").observe(.value, with: { (snapshot) in
for child in snapshot.children.allObjects as [FIRDataSnapshot] {
print (child.key)
ref.child("users/\(child.key)").observeSingleEvent(of: .value, with: { (userSnapshot) in
let content = userSnapshot.value as? [String : AnyObject] ?? [:]
print(content["name"])
})
}
})