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

时间:2018-05-13 20:15:14

标签: swift database firebase firebase-realtime-database

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

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 
    } 
  } 

1 个答案:

答案 0 :(得分:0)

这里的关键是,因为.value读取usersDatabase节点,迭代每个子节点并将其视为快照将为您提供计数。

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

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