【问题标题】:Swift Firebase -How to get all the k/v when using queryOrdered(byChild: ).queryEqual(toValue: )Swift Firebase - 使用 queryOrdered(byChild: ).queryEqual(toValue: ) 时如何获取所有 k/v
【发布时间】:2019-03-23 23:43:53
【问题描述】:
root
  |
  @--reviews
        |
        |
        @--postABC // postId
               |
               |
               @--reviewXYZ // ***I want everything under this reviewUID
               |    |
               |    |--buyerUID: "01010"
               |    |--text: "fast shipping!"
               |    |
               |    @--responseTUV // responseUID
               |         |
               |         |--sellerUID: "212555"
               |         |--text: "we aim to please"
               |     
               @--reviewEFG // this review is from a totally different user I don't want anything from here

我的数据库设置如上。有时我只有买家 uid,所以我使用 .queryOrdered(byChild: "buyerUID").queryEqual(toValue: "01010") 来提取数据,我可以从该特定帖子中找到买家并对其进行评论。

我如何在找到该节点(reviewXYZ) 后获取与买方相关的所有其他 k/v?

let reviewsRef = Database.database().reference()?
                   .child("reviews")
                   .child("postABC")
                   .queryOrdered(byChild: "buyerUID")
                   .queryEqual(toValue: "01010")

reviewsRef?.observeSingleEvent(of: .value, with: { [weak self](snapshot) in

    print(snapshot.key) // prints  postABC
    print(snapshot.value) // prints a dictionary with reviewXYZ as the key and everything underneath it as a value

    guard let dict = snapshot.value as? [String: Any] else { return }
})

【问题讨论】:

    标签: ios swift firebase firebase-realtime-database


    【解决方案1】:

    DataSnapshot class 具有循环遍历其子级的内置方法。

    reviewsRef?.observeSingleEvent(of: .value, with: { [weak self](snapshot) in
      for child in snapshot.children {
        let snap = child as! DataSnapshot;
        print(snap.key)
        print(snap.value) 
        print(snap.childSnapshot(forPath: "buyerUID").value)
      }
    })
    

    另见其他search results for looping over Firebase child nodes in Swift

    【讨论】:

    • 感谢它的工作。对于在 for 循环中使用它的任何其他人,只需将 child 转换为 Datasnapshot。例如-对于 snapshot.children 中的孩子 { let x = child as!数据快照;打印(x.key);打印(x.值); print(x.childSnapshot(forPath: “buyeyUID”).value) }
    • 感谢您分享正确的咒语 Lance!我更新了我的答案以反映这一点。
    • 由于您添加了数据快照,您可能希望删除您所说的句子,它可能会丢失它。这可能会让一些人感到困惑?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多