1

I am using firebase for simple chat application. I am looking to fetch messages of user 1 and user 2. My database structure look like this.

Database structure

I am using queryOrdered to fetch messages but it will filter with either sender or receiver.

 Database.database().reference().child("Chats").queryOrdered(byChild: "receiver")
                    .queryEqual(toValue: "2WCS7T8dzzNOdhEtsa8jnlbhrl12")
                    .observe(.value, with: { snapshot in

                    })

But using this code I got messages of receiver only. How can I receive messages of sender as well. Can I use AND condition to query sender child?

vikingosegundo
  • 52,040
  • 14
  • 137
  • 178
Ahsan Ali
  • 39
  • 5

1 Answers1

-1

There is no way in your current data structure to with a single query get both the messages that a specific user sent and received.


Firebase Database queries can only order/filter on a single property. In many cases it is possible to combine the values you want to filter on into a single (synthetic) property.

For example, you could combine the sender and receiver UID into a single properties "sender_receiver": "2WCS7T8dzzNOdhEtsa8jnlbhrl12_Sl91z...." and then query for that combined value.

For a longer example of this and other approaches, see my answer here: Query based on multiple where clauses in Firebase


For most chat applications however I recommend creating a database structure that models chat "rooms". So instead of having one long list of all messages, store the messages in rooms/threads, which is also what you show in the UI of your app.

"-RoomId1": {
  "msg1": { ... },
  "msg2": { ... }
}, "-RoomId2": {
  "msg3": { ... },
  "msg4": { ... }
}

That way you have the most direct mapping from the database, to what you show on the screen.

For a good way to name the "rooms", see Best way to manage Chat channels in Firebase

You'd then still store a mapping for each user of what rooms they're a part of, which might also be useful in securing access.

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807