问题
The firebase data structure is
{
"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"
}
}
}
I want to find all users who go to fm event. Here is my code:
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)
})
})
I follow this tutorial https://youtu.be/Idu9EJPSxiY?t=3m14s ,
Base on the tutorial snapshot.key
should return "1", "2", so that ref.child("users/\(snapshot.key)")
will be ref.child("users/1")
But on my code, the snapshot.key
return "fm", and ref.child("users/\(snapshot.key)")
will be ref.child("users/fm")
Where is the problem in my code?
回答1:
Under eventAttendees/fm
you have multiple children. So you will need to loop over those child nodes in your code too:
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"])
})
}
})
来源:https://stackoverflow.com/questions/44575427/joins-in-the-firebase-database