我的数据库方案基本上与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&#34)
我该怎么办?我尝试了Database.database().reference(withPath: "users").queryOrdered(byChild: "groups").queryEqual(toValue: "techpioneers")
,但这不起作用(显然)。
答案 0 :(得分:3)
要加载属于特定群组的所有用户,请在snmpCommunityTable
节点中开始以查找其密钥:
usmUserTable
它为您提供所有成员的钥匙。然后遍历这些键并加载相应的用户。
这实际上是一个客户端连接操作。虽然您最初可能认为这速度非常慢,但实际上并不是那么糟糕,因为Firebase会通过单个连接管理请求。请参阅http://stackoverflow.com/questions/35931526/speed-up-fetching-posts-for-my-social-network-app-by-using-query-instead-of-obse/35932786#35932786。
答案 1 :(得分:1)
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
}
}