我有一个类似这样的数据库。 我想如何比较所有用户的价值,以获得最大的价值。
restaurant
-userUid
-stateUid
-restaurantUid
-price = 9
-restaurantUid2
-price = 10
-stateUid2
-restaurantUid3
-price = 2
正如您在那里看到的数据库,stateUID
price是19,而stateUID2
price只有2,所以stateUID
的价格最大。 如何比较它们,显示最多的一个。 谢谢
编辑:
我做了类似的事情,在return
处是错误的。 而该值不起作用。
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);
});
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
}
}
}
);
使用嵌套的for循环从数据库中迭代,如上,并计算您的价格
另外,你可以做的是当你上传resto的数据时--上传价格时,只需为城市的总价多做一个节点,每次上传新的resto时添加resto的价格
Firebase查询在一个简单的节点列表上工作。 查询只能包含单个未知键,即查询所在位置下的直接子节点的键。 在您的数据结构中有多个未知键级别,这意味着您无法查询所有这些键的最高价格。
在当前的数据结构中,您所能做的是跨一个州查询价格最高的餐厅。 看起来像是:
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();
}
}
但是您不能在所有的州中搜索一个用户,甚至不能搜索所有的用户。 如果你想允许这样做,你必须将所有的价格存储在一个统一的列表中,比如:
restaurant_prices: {
"restaurantid": {
price: 9,
state: "statid",
user: "userid"
}
}
另请参阅: