0

I have a database something like this. How I want to compare the value for all users to get most value.

restaurant
    -userUid
        -stateUid
            -restaurantUid
                -price = 9
            -restaurantUid2
                -price = 10
        -stateUid2
            -restaurantUid3
                -price = 2
            

As you can see the database there, stateUid price is 19 while stateUid2 price is only 2 So, stateUid has the most price. How to compare them and display the most one. Thank you

EDIT:

I have done something like this, and it's error at return. And the value is not working.

exports.calculateTotal = functions.database.ref('/restaurant/{userUid}/{stateUid}/{restaurantUid}')
    .onWrite((change, context) => {
        // Only edit data when it is first created.
        if (change.before.exists()) {
            return null;
        }
        // Exit when the data is deleted.
        if (!change.after.exists()) {
            return null;
        }

        //Get id
        const restaurantUid = context.params.restaurantUid;

        let totalValue = 0;
        change.after.forEach(function (item) {
            totalValue += item.child('total').val();
        });
        console.log(totalValue);
        return functions.database.ref('/priceTotal/' + restaurantUid).child('total').set(totalValue);
    });
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
Ticherhaz FreePalestine
  • 2,738
  • 4
  • 20
  • 46

2 Answers2

1

Firebase queries work on a flat list of nodes. A query can contain only a single unknown key, the key of the direct child nodes under the location where you query. In your data structure there are multiple levels of unknown keys, which means that you can't query for the highest price across all of them.

What you can do in your current data structure is query across one state for the restaurant with the highest price. That'd look something like:

DatabaseReference ref = FirebaseDatabase.getInstance().getReference("restaurant");
DatabaseReference stateRef = ref.child("userUid").child("stateId");
stateRef.orderByChild("price").limitToLast(1).addListenerForSingleValueEvent(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        for (DataSnapshot snapshot: dataSnapshot.getChildren()) {
            Log.i(TAG, snapshot.getKey()+": "+snapshot.child("price").getValue(Long.class));
        }
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {
        throw databaseError.toException();
    }
}

But you can't search across all states for a user, or even all users. If you want to allow that, you'll have to store all prices in a flat list, like:

restaurant_prices: {
  "restaurantid": {
    price: 9,
    state: "statid",
    user: "userid"
  }
}

Also see:

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
0
int totalPrice = 0;
int greaterPrice = 0;
int temp = 0;

DatabaseRefernce restRef = FirebaseDatabase.getInstance().getReference().child("restaurant").child(userUid);

restRef.addValueEventListener(new ValueEventListener(){
       
    onDataChange(Datasnapshot snapshot) {
        
        for(Datasnapshot snap : snapshot) {
          
            String key = snap.getKey();
            //This will return you the keys of stateUid
            restRef.child(key).addValueEventListener(new ValueEventListener(){
                   
                   onDataChanged(DatSnapshot datasnapshot) {
    
                           //this for loop will iterate through restaurants of that specific state
                           for(DataSnapshot snap2 : datasnapshot){
                           
                                 totalPrice += (int) snap2..child("price").getValue();
                           
                           }
                           //When this loop ends you will get the total price of all restaurants from that state

                   }
                    
        
            });

           //as u see above I mentioned greater price and temp variable
           using simple logic of finding greatest number out of two number save the value of greatest integer to the variable every time you loop through state

        } 

    }

  }
);



Use nested for loops to iterate from database like above and calculate your prices

Else what you can do is when you are uploading the data of restos - while uploading prices just make an extra node for total price of city and add price of resto every time you upload new resto