Firebase: Retrieve nested data from unknown children

梦想与她 提交于 2020-01-26 03:23:05

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!