0

I have a data structure like this:

UserOrders
    unique-userid-100
        unique-orderid-456
            [order details here] 
        unique-orderid-123
            [order details here]
    unique-userid-200
        unique-orderid-789
            [order details here]
    ....

For admin functionalities, I need to query using the orderid (without knowing the userid) and get order details? How can I efficiently do this?

I tried this but I get all the data under UserOrders.

ref.child("UserOrders").queryOrdered(byChild: "unique-orderid-456").observeSingleEvent(...
SKT
  • 271
  • 4
  • 15

1 Answers1

2

Using Firebase API, we can only filter one level nested data.

So, for this first it will be needed to map users to there orders like :-

UserOrders

unique-userid-100

    unique-orderid-456 = true
    unique-orderid-123 = true
unique-userid-200
    unique-orderid-789 = true
....

Then find userid for an order using query :-

let ref  = FIRDatabase.database().reference()
        ref.child("UserOrders").queryOrdered(byChild: "unique-orderid-456").queryEqual(toValue: true).observeSingleEvent(of: .value, with: { (snapshot) in
  // here userid will be obtained for an order, using this ref/<userid>/unique-orderid-456 can be observed to get order details

})

This is a work around, but it will be good if you can reconsider to restructure data

Please refer similar:- Firebase Query Double Nested

Annie Dev
  • 282
  • 1
  • 10
  • The referenced post says "deep queries are now a feature" in Firebase – SKT Jan 22 '18 at 12:32
  • 1
    deep queries can be done when path is known, as in this post: https://firebase.googleblog.com/2015/09/introducing-multi-location-updates-and_86.html , without known userid, i believe it is not possible. – Annie Dev Jan 22 '18 at 12:35