0

I have a database managed solely via iOS of the following format in Firebase:

hotels/ hotel1/ guests/ *[RandomID]:guest1 [RandomID]:guest2 [RandomID]:guest3 location/ address ... hotel2/ guests/ [RandomID]:guest3 [RandomID]:guest4 location/ address ... hotel3/ guests/ location/ address ... hotel4/ guests/ [RandomID]:guest4 [RandomID]:guest5 location/ address ... hotel5/ guests/ [RandomID]:guest3 location/ address ... ...

My goal is to run a Swift command to return the set of 'hotels' that have a given guest. For example, checking for guest3 should return hotels 1, 2, and 5 with associated data. Something along the lines of this would typically work:

Query filterQuery = databaseReference.orderByChild("type").equalTo(true);

but unfortunately, it doesn't seem like there is an equivalent to the equalTo command in the iOS documentation. What is the best way to accomplish this task in the bounds of the iOS Firebase library then?

*The random IDs are generated automatically when the guest entry is inserted into the guests dictionary, as per this blog post: https://firebase.googleblog.com/2014/04/best-practices-arrays-in-firebase.html. It seems unintuitive, but apparently uniqueness must be ensured by assigning each element a unique ID generated at insertion time.

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
Alekxos
  • 512
  • 6
  • 13
  • 2
    David's answer is indeed the most common approach: store the data in both directions. I just answered a [question about this in an AskFirebase video](https://youtu.be/HjlQH3RsGcU?t=2m45s). If you're more a reader, here's the answer that video covers: http://stackoverflow.com/questions/41527058/many-to-many-relationship-in-firebase – Frank van Puffelen Jan 26 '17 at 08:59

2 Answers2

1

Couldn't you just have another set for users and then for each user have the hotels that they are a value of?

Something along these lines

users:
    - guest1:
        - hotels:
            - hotel1
            - hotel3
            - etc. etc.

I doubt it would be good to have to go through every hotel to see if it contains a certain user. This way you could just call the user based on their [RandomID] and get the hotels that way.

David
  • 77
  • 2
  • 10
0

try this code

let query = ref.queryOrderedByKey().queryEqual(toValue: guestID)
            query.observe(.childAdded, with: { (snapshot) in

            }

here ref = reference to hotels branch

rv7284
  • 1,092
  • 9
  • 25