【问题标题】:How to get childs whose arrays contain a certain value如何获取数组包含某个值的孩子
【发布时间】:2017-08-07 12:37:30
【问题描述】:

我有一个与documentation 基本相同的数据库方案:

// An index to track Ada's memberships
{
  "users": {
    "alovelace": {
      "name": "Ada Lovelace",
      // Index Ada's groups in her profile
      "groups": {
         // the value here doesn't matter, just that the key exists
         "techpioneers": true,
         "womentechmakers": true
      }
    },
    ...
  },
  "groups": {
    "techpioneers": {
      "name": "Historical Tech Pioneers",
      "members": {
        "alovelace": true,
        "ghopper": true,
        "eclarke": true
      }
    },
    ...
  }
}

我想创建一个DatabaseQuery 来获取属于特定组的所有用户(例如,“组”中包含“techpionneers”的用户)

我应该如何进行?我尝试了Database.database().reference(withPath: "users").queryOrdered(byChild: "groups").queryEqual(toValue: "techpioneers"),但这不起作用(显然)。

【问题讨论】:

    标签: ios swift firebase firebase-realtime-database


    【解决方案1】:

    要加载属于特定组的所有用户,请在/groups 节点中开始以找到他们的密钥:

    ref.child("groups/techpioneers/members").observeSingleEvent(of: .value, with: { (snapshot) in
    

    这会给你所有成员的钥匙。然后遍历这些键并加载相应的用户。

    这本质上是一个客户端连接操作。虽然您最初可能认为这非常慢,但实际上并不是那么糟糕,因为 Firebase 通过单个连接对请求进行管道传输。见http://stackoverflow.com/questions/35931526/speed-up-fetching-posts-for-my-social-network-app-by-using-query-instead-of-obse/35932786#35932786

    【讨论】:

      【解决方案2】:

      Franks 的解决方案是现成的,但另一种方法是使用Deep Query,即按深度路径排序以查询用户节点的子节点->匹配条件的子节点。这是格式

          let ref = self.ref.child("users")
          let query = ref.queryOrdered(byChild: "groups/techpioneers").queryEqual(toValue: true)
          query.observeSingleEvent(of: .value, with: { (snapshot) in 
              for child in snapshot.children {
                  let snap = child as! DataSnapshot
                  print(snap)
              }
          })
      

      结果是属于 techpioneers 组的所有用户

      "alovelace": {
         "name": "Ada Lovelace",
         "groups": {
            "techpioneers": true,
            "womentechmakers": true
            }
      }
      

      【讨论】:

      • 这是一个很好的答案,这样我就不必进行两次查询了。谢谢
      猜你喜欢
      • 2021-04-07
      • 2022-01-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-13
      • 1970-01-01
      • 1970-01-01
      • 2021-02-03
      相关资源
      最近更新 更多