gpt4 book ai didi

swift - Firebase以两种不同的方式获取子数据

转载 作者:行者123 更新时间:2023-11-30 11:30:25 25 4
gpt4 key购买 nike

我正在构建一个特定的数据库(下图),我想在标签中显示结果。第一个标签应显示所有客户的数量 - 这很简单,但第二个标签应显示所有 child 的客户的数量,例如:如果客户 Ben 有一个 child ,Tom 有一个 child - 标签显示 2(数字 child 的客户)。

enter image description here

可以这样做吗?

我的代码:

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

编辑:添加代码来计算和显示所有子节点的客户总数。

关于swift - Firebase以两种不同的方式获取子数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50320259/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com