BlueBear
BlueBear

Reputation: 23

How to get parent from child

So let's say I found that a value in database matches value entered by user through query. How can I find the parent of that value?

Ex. Let's say I enter in 35 as the age. 35 is also found in the database so how do I get the parent of that value (0)? Underlined in the picture.

I saw some similar questions asked but I can't seem to find a right answer to my question. Additionally, most of them are in different language.

enter image description here

Here is what I got so far:

 @IBAction func onDiagnose(_ sender: Any) {
        let ref1 = Database.database().reference(fromURL: "https://agetest.firebaseio.com/")
        let databaseRef = ref1.child("data")
        databaseRef.queryOrdered(byChild: "age").queryEqual(toValue: Int(ageTextField.text!)).observeSingleEvent(of: .value, with: { (snapshot) in
            // if there is data in the snapshot reject the registration else allow it

            if (snapshot.value! is NSNull) {


               print("NULL")

            } else {


                //print(snapshot.value)
                //get parent
                //snapshot.ref.parent?.key! as Any
            }


        }) { (error) in
            print(error.localizedDescription)
        }

    }

Upvotes: 0

Views: 283

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 599956

When you execute a query against the Firebase Database, there will potentially be multiple results. So the snapshot contains a list of those results. Even if there is only a single result, the snapshot will contain a list of one result.

So you need to loop through the child nodes of the resulting snapshot to get at the individual results:

databaseRef.queryOrdered(byChild: "age").queryEqual(toValue: Int(ageTextField.text!)).observeSingleEvent(of: .value, with: { (snapshot) in
    for child in snapshot.children.allObjects as! [DataSnapshot] {
        print(child.key)     
    }
}) { (error) in
    print(error.localizedDescription)
}

Also see listening to value events for lists of data in the Firebase documentation.

Upvotes: 1

Related Questions