简体   繁体   中英

Firebase Access a children if I don't know two childs who have unknown ids

How can I access the data of the children memberId or name and photoURL of the child "members"? You can see the structure of my database in images. 在此处输入图片说明

在此处输入图片说明

I tried to use queryOrdered and queryEqual but I just can use it one time

I tried like that because I know the room.key who is the "key" on the database.

let refParticipants = refDatabase.child("markers").queryOrdered(byChild: "key").queryEqual(toValue: room.key)
    refParticipants.observe(.childAdded, with: { snapshot in
...
}

I use Swift 3.1

I update my answer with that screenshot: 在此处输入图片说明

I think you are asking how to access the child nodes of

/markers/oHQ.../members/9oBKY...

Let's simply the structure for this answer

markers
  marker_0
   members
     member_0
       name: "J"
     member)1
       name: "K"

and then the code that will access each member within the members node and print their name

let markersRef = self.ref.child("markers")
let marker0Ref = markersRef.child("marker_0")
let membersRef = marker0Ref.child("members")
membersRef.observeSingleEvent(of: .value, with: { snapshot in
    for child in snapshot.children {
        let snap = child as! DataSnapshot
        let dict = snap.value as! [String: Any]
        let name = dict["name"] as! String
        print(name)
    }
})

and the output will be

J
K

Since you know the parent node (oHQa...), which contains the child node 'members', it doesn't really matter as to what each members key is since you are iterating over them.

However, if you are wanting to query for certain members or other member data, you may want to consider flattening the database a bit like this

markers
  oHQa...
    //marker data
marker_members
  member_0
     name: "J"
     member_of: "oHQa..."
  member_1
     name: "K"
     member_of: "oHQa..."

With this structure you can query for all the members of any marker or query for all members whose name is "J" etc.

As a side note, in the structure in the question you have the member_id as both the key as well as a child which is unnecessary. If it's the key then you can always directly access that node without a query.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM