我正在构建一个特定的数据库(下图),我想在标签中显示结果。第一个标签应该显示所有客户的数量 - 这很简单,但第二个标签应该显示所有孩子的客户数量,例如:如果客户 Ben 有一个孩子,而 Tom 有一个孩子 - 标签显示 2(数字孩子的客户)。
有可能做到这一点吗?
我的代码:
let userID = Auth.auth().currentUser!.uid
ref.observeSingleEvent(of: .value, with: { snapshot in
if let allServices = snapshot.childSnapshot(forPath: "usersDatabase/(userID)/Customers").value {
if snapshot.childrenCount == 0 {
self.servicesLabel.text = "0"
} else {
self.servicesLabel.text = (allServices as AnyObject).count.description
}
}
这里的关键是,由于 usersDatabase 节点是由 .value 读取的,因此遍历每个子节点并将其视为快照将为您提供计数。
let usersDatabaseRef = Database.database().reference().child("usersDatabase")
usersDatabaseRef.observe(.value, with: { snapshot in
print("there are \(snapshot.childrenCount) users")
var totalCustomerCount = 0
for child in snapshot.children {
let childSnap = child as! DataSnapshot
let childrenRef = childSnap.childSnapshot(forPath: "Customers")
totalCustomerCount += Int(childrenRef.childrenCount)
print("user \(childSnap.key) has \(childrenRef.childrenCount) customers")
}
print("... and there are \(totalCustomerCount) total customers")
})
假设usersDatabase节点有3个用户,会打印如下
there are 3 users
user uid_0 has 2 customers //this is the 7U node
user uid_1 has 1 customers
user uid_2 has 3 customers
... and there are 6 total customers
编辑:添加了代码来计算和显示所有子节点的客户总数。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句