如何从孩子那里获得父母

时间:2019-01-24 22:40:36

标签: swift firebase firebase-realtime-database

因此,假设我发现数据库中的值与用户通过查询输入的值匹配。如何找到该值的父级?

例如假设我输入的年龄是35岁。在数据库中也找到35,那么如何获得该值(0)的父级?图片中带有下划线。

我看到了一些类似的问题,但似乎找不到正确的答案。此外,大多数语言都是不同的。

enter image description here

这是我到目前为止所得到的:

 @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)
        }

    }

1 个答案:

答案 0 :(得分:1)

对Firebase数据库执行查询时,可能会有多个结果。因此,快照包含这些结果的列表。即使只有一个结果,快照也会包含一个结果的列表。

因此,您需要遍历结果快照的子节点以获得单独的结果:

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)
}

另请参阅Firebase文档中的listening to value events for lists of data

相关问题