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

Swift Firebase以两种不同的方式获取子数据,swift,database,firebase,firebase-realtime-database,Swift,Database,Firebase,Firebase Realtime Database,我正在建立一个特定的数据库(下图),我想在标签中显示结果。第一个标签应该显示所有客户的数量——这很简单,但第二个标签应该显示所有儿童客户的数量,例如:如果客户Ben有一个孩子,Tom有一个孩子——标签显示2(儿童客户的数量) 有可能做到这一点吗 我的代码: let userID = Auth.auth().currentUser!.uid ref.observeSingleEvent(of: .value, with: { snapshot in if let allServices

我正在建立一个特定的数据库(下图),我想在标签中显示结果。第一个标签应该显示所有客户的数量——这很简单,但第二个标签应该显示所有儿童客户的数量,例如:如果客户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节点中有三个用户,将打印以下内容

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

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

听起来可能。您能否显示在实现此功能时遇到问题的代码?@FrankvanPuffelen let userID=Auth.Auth().currentUser!。uid ref.observeSingleEvent(of:.value,带:{snapshot in if let allServices=snapshot.childSnapshot(forPath:“usersDatabase/(userID)/Customers”)。值{if snapshot.childrenCount==0{self.servicesLabel.text=“0”}else{self.servicesLabel.text=(所有服务作为任何对象).count.description}}let userID=Auth.Auth().currentUser!.uid let usersDatabaseRef=Database.Database().reference().child(“usersDatabase”).child(userID).child(“客户”)usersDatabaseRef.observe(.value,带:{正在打印的快照(“有(snapshot.childrenCount)用户”)self.clientsLabel.text=snapshot.childrenCount.snapshot.childrenCount.description for child in snapshot.childrensnap{let childSnap=childas!DataSnapshot let childrenRef=childSnap.childrenCount打印(“用户(childSnap.key))(childrenRef)customers)在稍加修改后,这段代码可以工作!但有一个问题-如何在客户的标签计数中显示(在您的示例中:6)?@KrzysztofŁowiec不确定我是否理解这个问题-您问的是一个标签-哪个标签?像UI中的静态文本标签?每个用户的客户计数都不同(我假设)那么你想在哪里看到这个计数?我在UI中有其他静态标签,我想在其中显示我所有用户的计数之和。有可能吗?@KrzysztofŁowiec我回答中的代码显示了所有用户的计数,其中显示有3个用户。这就是你要问的计数吗?