【发布时间】:2017-11-15 15:18:51
【问题描述】:
groups
--group1(autoid)
---subgroup1(autoid)
----id
----ownerId
----description
--group2(autoid)
---subgroup2(autoid)
----id
----ownerId
----description
在像这里这样的结构中,我必须计算所有组中所有与我的 id (currentUserId) 相等的 ownerId 的出现次数,有人可以帮助我吗?
到目前为止我做了什么:
root.child("groups").observe(.value, with: {(snapshot) in
if let result = snapshot.children.allObjects as? [DataSnapshot] {
var count = 0
for child in result {
let orderID = child.key as String //get autoID
self.root.child("groups/\(orderID)/").queryOrdered(byChild: "ownerId").queryEqual(toValue: self.currentUserId).observe(.value, with: { (snapshot: DataSnapshot!) in
print(snapshot.childrenCount, "quanti sono")
count += (Int(snapshot.childrenCount))
print(count)
})
}
}
})
有了这个我可以得到一个计数,但它会更新所有周期......我需要我需要外面的最终值
【问题讨论】:
-
欢迎来到 Stack Overflow!使用实际数据示例、预期结果和实际结果更新您的问题会很有帮助。在此处了解如何制作最小、完整和可验证的示例:stackoverflow.com/help/mcve
-
我想说的是如何存储组数是问题所在。该查询涉及子查询,过于复杂,无法得到简单的结果。为什么不直接在数据库中存储用户所属的组数?示例用户 -> UID -> GroupMemberCount?然后,您可以在用户加入/离开组时更新此值。这将使整个过程更容易。 snapshot.childrenCount 还会遍历所有子节点,因此如果用户是许多组的成员,它可能效率不高。
标签: swift firebase firebase-realtime-database