数据库值计数 [英] Database count of values

查看:29
本文介绍了数据库值计数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的数据库结构为 userDatabase/userID/Customers ,我有两个客户.例如路径:

I my database structure userDatabase/userID/Customers I have two customers. For example path:

usersDatabase
    g8voYf1yoChnpmhkoPgtmO4FQT62 - (uid)
        Customers
            Tom Smith (customer with custom ID)
                -LDFZw1tca8KOrnqyyWH - (auto id of customer child)
                    Status of Service: "Open service"
            Ben Thomas (customer with custom ID)
                -LDFZw1tca8KOjgoenBN - (auto id of customer child)
                    Status of Service: "Open service"

是否可以从数据库中的所有客户获取开放式服务"的价值计数?现在我只知道,如何为每个客户打印此值...

Is possible to fetch count of value "Open service" form all customers in my database? Now I only know, how to print this value for each customers...

我的代码从数据库中获取价值:

My code to get value from Database:

let userID = Auth.auth().currentUser?.uid
    let usersDatabaseRef = Database.database().reference().child("usersDatabase").child(userID!).child("Customers")
    usersDatabaseRef.observe(.value, with: { snapshot in
        var totalCustomerCount = 0
        for child in snapshot.children {
            let childSnap = child as! DataSnapshot
            let childrenRef = childSnap
            totalCustomerCount += Int(childrenRef.childrenCount)
            print("user \(childSnap.key) has \(childrenRef.childrenCount) customers")

            let userCustomerSnap = childSnap
            for customer in userCustomerSnap.children.allObjects as! [DataSnapshot] {
                let customerSnap = customer
                let dict = customerSnap.value as! [String: Any]

                let stat = dict["Status of Service"] as! String

                let myStatistic = PrintModel(status: stat)
                self.statistic.append(myStatistic)
                print("Statistic: \(String(describing: myStatistic.status))")
            }
        }
        print("... and there are \(totalCustomerCount) total customers")
    })

例如,我的日志现在显示:

For example my log now show:

  1. 用户Tom Smith有1个客户
  2. 统计信息:可选(开放式服务")
  3. 用户Ben Thomas有1个客户
  4. 统计信息:可选(开放式服务")

但我想显示:

  1. 统计数据:2

推荐答案

在构造Firebase数据时,该结构通常基于您想要获得的数据.在这种情况下,所需的数据在发布的结构中太深而无法使用.因此,更改结构将使其变得轻而易举.

When structuring Firebase data, the structure is generally based on what you want to get out of it. In this case the data you want is too deep within the posted structure to be useful. So, changing the structure will make this a snap.

将数据分离到自己的节点中,从而对数据进行非规范化.像这样

Separate your data into their own nodes, denormalizing the data. Like this

users
   uid_0
     //some  info about this user
     open_service_calls
          auto_id_0: true
          auto_id_1: true
   uid_1
     //info about this user

customers
    customer_id_0
      customer_name: "Tom Smith"
      open_service_calls
          auto_id_0: true
    customer_id_1
      customer_name: "Ben Thomas"
      open_service_calls
          auto_id_1: true

service_calls
   auto_id_0
      customer_id: customer_id_0
      user_id: "uid_0"
      status_of_service: "Open service"
   auto_id_1
      customer_id: customer_id_1
      user_id: "uid_0"
      status_of_service: "Open service"

这允许按客户,用户进行查询,并解决该问题,从而轻松地为所有用户和客户计算数据库中的所有Open Service;在service_calls/status_of_service中查询开放服务"

That allows for queries by customer, user, and to address this question, an easy count of all Open Service in the database for all users and customers; query the service_calls/status_of_service for "Open service"

它还允许您快速访问所有服务呼叫,无论是为任何用户,任何客户打开还是关闭,甚至只是为用户客户打开服务呼叫.

It also allows you to quickly access all service calls, open or closed for any user, any customer and even just open service calls for a users's customer.

其他节点将提供进一步的查询灵活性-将用户ID存储在客户节点内将使超级简单的查询可以检索特定用户的所有客户,即使他们没有服务呼叫;这完全取决于您要从Firebase中获得什么.

Additional nodes would offer further query flexibility - storing the user id within the customer node would allow a super easy query to retrieve all of the customers for a specific user even if they have no service calls; it all depends on what you want to get out of Firebase.

---旧答案在---

根据我对原始问题的评论,此答案涉及使用深度查询来查询客户子节点的子代.这里的想法是,在用户节点中,有一个客户"节点,其中每个子键是一个客户名称,而该节点的值是一个键:字符串"serviceID"的值对,然后是一个可能包含其他子节点的值关于服务.

Per my comment to the original question, this answer involves using a Deep Query to query a child of child node of customers. The idea here is that within the user node, there's a Customers node where each child key is a customer name and the value of that node is a key: value pair of the string "serviceID" and then a value which may contain other child nodes about the service.

深度查询的重要部分是保持要查询的子键的名称一致-在这种情况下,我们使用键"serviceID",以便查询可以正确解析路径,然后解析任何子节点可以查询:status_of_service,可能是时间戳,甚至是服务位置

The important part of a Deep Query is to keep the child keys you are query'ing named consistently - in this case we use the key 'serviceID' so the query can properly resolve the path and then any of the child nodes of that can be queried: status_of_service, perhaps a time stamp or even the service location

更改之前的初始结构是

Customers
  Tom Cruise
      serviceID
         status_of_service: "Open service"
         //timestamp of service?
         //location of service?
         //other data about service we may need to query?
  Ben Smith
      serviceID:
         status_of_service: "Open service"

请注意,对于此答案,self.ref =我的基地,因此客户"是该路径的直接子代.

Note that for this answer self.ref = my firebase so Customers is a direct child of that path.

let ref = self.ref.child("Customers")
let query = ref.queryOrdered(byChild: "serviceID/status_of_service")
               .queryEqual(toValue: "Open service")
query.observeSingleEvent(of: .value, with: { (snapshot) in 
    for child in snapshot.children {
        let snap = child as! DataSnapshot
        print(snap)
    }
})

输出是两个客户节点

   tom_smith
      serviceID
        status_of_service: "Open service"
   another_customer
      serviceID
        status_of_service: "Open service"

这篇关于数据库值计数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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