Joins in the Firebase Database

安稳与你 提交于 2021-02-04 06:30:07

问题


The firebase data structure is

{
  "eventAttendees" : {
    "fm" : {
      "1" : "David",
      "2" : "Alice"

    }
  },
  "events" : {
    "fm" : {
      "date" : "2017-06-16",
      "name" : "Firebase Meetup"
    },
    "gm" : {
      "date" : "2017-08-12",
      "name" : "Meet Linh"
    }
  },
  "users" : {
    "1" : {
      "email" : "david@gmail.com",
      "name" : "David"
    },
    "2" : {
      "email" : "alice@gmail.com",
      "name" : "Alice"
    },
    "10" : {
      "email" : "khanh@gmail.com",
      "name" : "Khanh"
    }
  }
}

I want to find all users who go to fm event. Here is my code:

let ref = Database.database().reference()
ref.child("eventAttendees/fm").observe(.value, with: { (snapshot) in
           print (snapshot.key)
            ref.child("users/\(snapshot.key)").observeSingleEvent(of: .value, with: { (userSnapshot) in
                let content = userSnapshot.value as? [String : AnyObject] ?? [:]
                print(content)
            })
        })

I follow this tutorial https://youtu.be/Idu9EJPSxiY?t=3m14s ,

Base on the tutorial snapshot.key should return "1", "2", so that ref.child("users/\(snapshot.key)") will be ref.child("users/1")

But on my code, the snapshot.keyreturn "fm", and ref.child("users/\(snapshot.key)") will be ref.child("users/fm")

Where is the problem in my code?


回答1:


Under eventAttendees/fm you have multiple children. So you will need to loop over those child nodes in your code too:

let ref = Database.database().reference()
ref.child("eventAttendees/fm").observe(.value, with: { (snapshot) in
    for child in snapshot.children.allObjects as [FIRDataSnapshot] {
        print (child.key)
        ref.child("users/\(child.key)").observeSingleEvent(of: .value, with: { (userSnapshot) in
            let content = userSnapshot.value as? [String : AnyObject] ?? [:]
            print(content["name"])
        })
    }
})


来源:https://stackoverflow.com/questions/44575427/joins-in-the-firebase-database

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!