从数据库中获取所有子项

时间:2018-05-17 05:06:56

标签: swift firebase firebase-realtime-database firebase-authentication

在我的应用程序中是tableview,我想显示我的客户的所有孩子。这是数据库结构:

enter image description here

以前在Customers我只有一个孩子时,我知道如何在路径为usersDatabase/userID/Customers时向客户展示。但是在这一刻我的路径是usersDatabase/userID/Customers/userSpecificName,我的tableview显示空白单元格。我必须在代码中添加什么来正确处理代码?

这是从数据库导入数据时的代码:

let userID = Auth.auth().currentUser!.uid
    ref = Database.database().reference().child("usersDatabase").child(userID).child("Customers")

    ref.observe(DataEventType.value, with: { (snapshot) in
        if snapshot.childrenCount > 0 {
            self.services.removeAll()
            self.filteredServices.removeAll()
            for results in snapshot.children.allObjects as! [DataSnapshot] {
                let results = results.value as? [String: AnyObject]
                let name = results?["Name and surname"]
                let phone = results?["Phone"]
                let customerID = results?["ID"]

                let myCustomer = CustomerModel(name: name as? String, phone: phone as? String, customerID: customerID as? String)
                self.services.append(myCustomer)
                self.filteredServices.append(myCustomer)
            }
            self.tableView.reloadData()
        }
    })

我应该添加到行 ref = Database.database()。reference()。child(“usersDatabase”)。child(userID).child(“Customers”) tableview show child增加了客户(Ben Smith和Tom Cruise)?

1 个答案:

答案 0 :(得分:0)

此答案类似于先前的答案here

您要做的是将客户中的每个孩子视为DataSnapshot,然后可以访问孩子。

给定Firebase结构:

Person

打印出每个用户及其客户的代码是

Age

和输出

String

编辑:OP想知道如何到达每个客户下的数据节点,所以这里有一个带输出的略微修改版本

usersDatabase
  uid_0
     Customers
        Ben Smith
           data: "Some data"
        Tom Cruise
           data: "Some data"
  uid_1
     Customers
        Leroy Jenkins
           data: "Some data"
  uid_2
     Customers
        De Kelly
           data: "Some data"
     etc

和输出

let usersDatabaseRef = Database.database().reference().child("usersDatabase")
usersDatabaseRef.observe(.value, with: { snapshot in
    print("there are \(snapshot.childrenCount) users")
    for child in snapshot.children {
        let childSnap = child as! DataSnapshot
        print("user: \(childSnap.key)")
        let userCustomerSnap = childSnap.childSnapshot(forPath: "Customers")
        for customer in userCustomerSnap.children {
            let customerSnap = customer as! DataSnapshot
            print(" customer: \(customerSnap.key)")
        }
    }
})