0

I want to perform a query to a firebase database.

My database is as follows:

database

I want to query "paymentStatus" by orderByChild value "paid".

How will my query code look? The below code not reading.

Query query = FirebaseDatabase.getInstance().getReference().child("Visits")
       .orderByChild("paymentStatus").equalTo("Paid");

Thank you in advance.

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

1 Answers1

1

Firebase database queries function on a list of child nodes, not on a tree. The database takes each direct child node under the location you query and then sorts/filters on the property you indicate.

There is no property paymentStatus directly under the child nodes of Visits, because the paymentStatus is one level deeper. That means that in your current data model, the query you want is not possible. If you want to filter visits by paymentStatus you will need to ensure that you have a single, flat list of visits.

Also see my answer to Firebase Query Double Nested.

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
  • So what's your suggestion to re-structure the database? The admin has to view all visits of all users. It's easy to view visits for each user because we know the ID, but it's not for admin as we have many IDs. Appreciate your answer and keep in mind I'm new to firebase. Thanks – الاحتراف الهندسي العالمية EPG Jan 26 '19 at 06:12
  • If you want to query visits across all users, you will need a top-level list of visits. If you want to show the visits for a user, you can either query for that in the top-level list, or (more commonly) also have the visits for each user in a separate list. So you'd end up with `/Visits/$visitId`, and `/UserVisits/$uid/$visitId`. You can either duplicate the data under `/UserVisits` or (if you don't need to query the visits for a specific user) you can just store the `$visitId`s with a value of true. Note that this is pretty much what my other answer says, but then mapped to your problem. – Frank van Puffelen Jan 26 '19 at 15:13
  • If you're new to NoSQL databases/Firebase, I highly recommend reading [NoSQL data modeling](https://highlyscalable.wordpress.com/2012/03/01/nosql-data-modeling-techniques/) and watching [Firebase for SQL developers](https://www.youtube.com/playlist?list=PLl-K7zZEsYLlP-k-RKFa7RyNPa9_wCH2s). – Frank van Puffelen Jan 26 '19 at 15:14