问题
I have a firebase structure like this
"broadcast": {
"ghjghjFc1S3KO0y8yJwORdfgret": { //user ID
"ryrtybgzMiI858YyGua": { //broadcast ID
"a": "xxx", // broadcast Detail
"b": "yyy",
"c": false
}
"cbvbcvbMvAnSDqTb15vU": { //broadcast ID
"a": "xxx", // broadcast Detail
"b": "yyy",
"c": true
}
}
"3uqWZJRFc1S3KO0y8yJwORTMtWC2": { //user ID
"jkhjkbgzMiI858YyGua": { //broadcast ID
"a": "xxx", // broadcast Detail
"b": "yyy",
"c": false
}
"qwwerqweMvAnSDqTb15vU": { //broadcast ID
"a": "xxx", // broadcast Detail
"b": "yyy",
"c": true
}
}
}
I want to retrieve all nodes having broadcasts where c is equal to true. How can I do this in swift?
回答1:
One way you could do this is by restructuring your database:
"userBroadcasts": {
"ghjghjFc1S3KO0y8yJwORdfgret": { // user ID
"ryrtybgzMiI858YyGua": true, // broadcastID
"jkhjkbgzMiI858YyGua": true, // another broadcastID
// etc..
},
// more users down here...
}
"broadcast": {
"ryrtybgzMiI858YyGua": { // broadcast ID
"a": "xxx", // broadcast Detail
"b": "yyy",
"c": false
},
"jkhjkbgzMiI858YyGua": {
"a": "xxx",
"b": "yyy",
"c": true
},
// more broadcasts down here...
}
Then you can get all the broadcasts you want by calling:
FIRDatabase.database().reference().child("broadcast").queryOrdered(byChild: "c").queryEqual(toValue: true)
If you want the userID as well, store this inside the broadcast when you create it, for example:
"broadcast": {
"ryrtybgzMiI858YyGua": { // broadcast ID
"a": "xxx", // broadcast Detail
"b": "yyy",
"c": false,
"userID":"ghjghjFc1S3KO0y8yJwORdfgret"
},
"jkhjkbgzMiI858YyGua": {
"a": "xxx",
"b": "yyy",
"c": true,
"userID":"ghjghjFc1S3KO0y8yJwORdfgret"
},
// more broadcasts down here...
}
Embrace denormalisation with the Firebase Database!
来源:https://stackoverflow.com/questions/44000332/firebase-retrieve-nested-data-from-unknown-children