Query in firebase Database in iOS

94 views Asked by At

I work with firebase database, I have the following data,

enter image description here

I need to get all groups names (GName) of a user by his phoneNum, i.e. all groups of specific user, How can I get that in swift 4?

1

There are 1 answers

3
Mert Ozdal On

You should consider restructuring your data. If a user belongs to more than one group in your application then you'll probably have to duplicate your user node for every group the user belongs to in your data structure. You can create another JSON object that holds all of the groups that a user belongs to. Here is a sample JSON for you:

{
    "users": [{
        "xyz123": {
            "userId": "xyz123",
            "username": "user1",
            "phoneNum": "123456",
            "groups": [{
                "groupId": 1,
                "groupName": "aaa"
            }, {
                "groupId": 2,
                "groupName": "bbb"
            }]
        }
    }]
}

As for filtering with the phone number, you can get all users inside a list and filter the result with the phone number criteria

result = result.filter({item.phoneNum == "123456"})

or get phone number of the user to a upper level, call .child() method with the phone number criteria and fetch the specific user.

Also take a look at structuring data part at firebase documentation.

https://firebase.google.com/docs/database/ios/structure-data

Hope that helps.