Swift Firebase - 如何在使用 queryOrdered(byChild: ).queryEqual(toValue: ) 时获取所有 k/v

2024-05-13

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

The DataSnapshot class https://firebase.google.com/docs/reference/swift/firebasedatabase/api/reference/Classes/DataSnapshot有内置方法来循环其子项。

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

另请参阅其他在 Swift 中循环 Firebase 子节点的搜索结果 https://www.google.com/search?q=firebase+swift+loop+over+children.

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Swift Firebase - 如何在使用 queryOrdered(byChild: ).queryEqual(toValue: ) 时获取所有 k/v 的相关文章

随机推荐