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:
- user Tom Smith has 1 customers
- Statistic: Optional("Open service")
- user Ben Thomas has 1 customers
- Statistic: Optional("Open service")
but I want to show:
- Statistic: 2