Poke Poke - 5 months ago 23
Swift Question

swift firebase retrieve all object that the child of the object have the same key

Below is my firebase and code , I would like to retrieve all activities which have the User John key inside User.
ss

let ref = FIRDatabase.database().reference().child("activities/")
ref.queryOrderedByChild("User").queryEqualToValue("John").observeSingleEventOfType(.Value,
withBlock:{
(snapshot) in

for record in snapshot.children
{

}
})

Answer

This is not working because in your query you are trying to take all the activities having an attribute User == "John" when the real value of User is an Object like this:

{ 
  "John": {
    "age": 21
  }
}

To solve this issue you should change your data structure creating a node where you save all your users, and keep in users/userID/activities only the id of the activities. For example, this would be a nicer way to structure your data:

{
    "activities": {
        "cycling": {
            "users": {
                "user1": true,
                "user2": true
            }
        },
        "running": {
            "users": {
                "user1": true
            }
        }
    },
    "users": {
        "user1": {
            "name": "John",
            "age": 21,
            "activities": {
                "cycling": true,
                "running": true,
            }
        },
        "user2": {
            "name": "Tim",
            "age": 20,
            "activities": {
                "cycling": true
            }
        }
    }
}

Then you can use Let me know if this helped ;)