4

Current Firebase DB Structure:

Current Firebase DB Structure

What I'm trying to achieve:

  • Search in any "promotions" child in all my places for a coupon equalTo something.
  • If found, update its "limit" parameter by decreasing it by -1

My current code:

    mDatabase = FirebaseDatabase.getInstance().getReference("Place");
    Query query = mDatabase.child("promotions").orderByChild("coupon").equalTo("FREEBIGMAC");
    query.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            for (DataSnapshot snapshot: dataSnapshot.getChildren()) {
                // Not able to find anything here

            }

        }

        @Override
        public void onCancelled(DatabaseError databaseError) {
            System.out.println("The read failed: " + databaseError.getMessage());
        }
    });

I have been trying to find a similar example under StackOverFlow but I haven't been able to find my exact case. I would really appreciate your help!

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
Juan Pablo
  • 93
  • 1
  • 6

1 Answers1

2

The Firebase Database can only query properties at a known path under each child node of the place where you execute the query. It cannot handle dynamic paths, as you are trying to do here.

For a longer explanation of this, see my answer here: Firebase Query Double Nested. This also seems relevant: Firebase query if child of child contains a value.

The solution is to denormalize your data, and unnest the promotions from the places. If you have a single list of promotions, you can get all of the ones who have a free big mac:

mDatabase = FirebaseDatabase.getInstance().getReference("Promotions");
Query query = mDatabase.orderByChild("coupon").equalTo("FREEBIGMAC");
query.addListenerForSingleValueEvent(new ValueEventListener() {

Now if you add a Place to each promotion, you can show all places that have free big macs.

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