swift - 如何从 child 那里得到 parent

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

    }

最佳答案

当您对 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)
}

另见 listening to value events for lists of data在 Firebase 文档中。

关于swift - 如何从 child 那里得到 parent ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54356435/

相关文章:

reactjs - 如何在 React 中按日期对 firebase 文档进行排序?

javascript - 如何以map firestore web的形式将集合中具有值的所有文档推送到另一个集合

flutter - 如何在不重新运行FirebaseAnimatedList的情况下更改AppBar 'title:'值

firebase - Firebase 模拟器中的时间戳不允许 (.) 点

swift - 如何减少此 Swift 函数中返回 false 的次数

ios - 在静态函数中传递 Self

ios - 在 Swift 中使用 touchesBegan

ios - Xcode 10 - 无法本地化 UINavigationController 标题

json - 将 firebase 生成的 json 数据集导入 mongodb

java - DataSnapshot for 循环 (Android Studio) 未附加 Firebase 数据库路径的子项