Oniikal3 Oniikal3 - 3 months ago 119
Swift Question

How can I retrieve data with queryEqualToValue in auto id child. Firebase-iOS

As my question. I can't retrieve data from firebase when I try to use "queryEqualToValue" with auto id key.

self.ref.child(..my child..).queryOrderByChild("name").queryEqualToValue("my name")


auto child id above child "name".

Edit: for my json tree


  • Students


    • (auto id)


      • name


        • first name

        • nick name






My real data doesn't like this but this's for example structure.
I really want to check equal to "first name".

Here's my code

let ref = FIRDatabase.database().reference()
ref.child("Students").queryOrderedByChild("name").queryEqualToValue("Jason bourne").observeEventType(.Value, withBlock: { snapshot in
print("value : " + snapshot.value)
}

Answer

Given your realtime database looks something like this:

{
    "students": {
        1: {
            "name": {
                "first_name": "Nathapong",
                "nick_name": "Oniikal3"
            }
        }
    }
}

You can observe the students path with the event type ChildAdded and order the query by child key name/first_name. Then you can use queryEqualToValue to find students with a particular first name.

let ref = FIRDatabase.database().referenceWithPath('students').queryOrderByChild("name/first_name").queryEqualToValue("Nathapong")

ref.observeSingleEventOfType(.ChildAdded, block: { snapshot in
    print(snapshot)
})