Firebase以两种不同方式获取子数据 [英] Firebase fetching child data for two different ways

查看:86
本文介绍了Firebase以两种不同方式获取子数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm building a specific database (picture below) and I want to display the results in the labels. The first label should show the number of all customers - it's simple, but the second label should show the number of all the child's clients, for example: if the customer Ben has one child, and Tom has one child - label shows 2 (number of child's clients).

可以这样做吗?

我的代码:

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


推荐答案

此处的关键是因为users.Database节点由.value读取,遍历每个子节点并将其视为快照将为您提供计数。

The key here is that since the usersDatabase node is read by .value, iterating over each child node and treating it as a snapshot will give you the counts.

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节点中有三个用户,将打印以下内容

asssuming there are three users in the usersDatabase node, will print the following

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

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

added code to count and display total customers across all child nodes.

这篇关于Firebase以两种不同方式获取子数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆