Joe Sloan
Joe Sloan

Reputation: 775

Accessing child IDs within user IDs in Firebase

I have a firebase database with the following structure, with the top ID shown being a user's UID:

enter image description here Although this example shows only 2 menu items, most of my users will have more than 10. If I wanted to create a list of all of the menu item names, what would that query look like in Swift? More specifically, what would that path look like in swift? Currently, my path makes it this far:

var itemNameRef = Firebase(url: "https://*******.firebaseIO.com/users/\(ref.authData.uid)/menu/")

Is there an ID placeholder similar to authdata.uid which I can place in the space after "menu?

Previously and under a different structure, using a [for] loop I was able to get the item names stored as children under "menu",with item details stored beneath that. But based on advice from another SO user, I've swapped to random keys and am back to square one.

Am I doing this the right way?

Thanks!

Upvotes: 0

Views: 1031

Answers (1)

Julian Lee
Julian Lee

Reputation: 263

To query a list of menu item names as you have it now:

var rootRef = Firebase(url: "https://*******.firebaseIO.com")
let menuItems = rootRef.childByAppendingPath(UID).childByAppendingPath("menu")
menuItems.observeSingleEventOfType(.Value, withBlock: { snapshot in
    for id in snapshot.children.allObjects as! [FDataSnapshot] {
        //do what you want
    }
}

Also, for best practice, try to build a "flat" database structure for Firebase (see https://www.firebase.com/docs/web/guide/structuring-data.html).

Upvotes: 1

Related Questions