android - Firebase 实时数据库将子笔记中的值与另一个子笔记进行比较
问题描述
我有一个类似这样的数据库。我想如何比较所有用户的价值以获得最大价值。
restaurant
-userUid
-stateUid
-restaurantUid
-price = 9
-restaurantUid2
-price = 10
-stateUid2
-restaurantUid3
-price = 2
正如你可以看到那里的数据库, stateUid
价格是 19 而stateUid2
价格只有 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);
});
解决方案
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"
}
}
另见:
推荐阅读
- sql - 如何使用sql将一个表中的多个列更新到另一个表。
- matlab - 在 Matlab 中,A(1) 是什么意思?如果 A 是矩阵
- amazon-web-services - 如何解决 AWS 微服务的 Rate Exceed 错误?
- jmeter - 当我导航到 JMter 中的单个页面时,视图结果树显示单个页面的三个隔离。请协助
- postgresql - 如何避免`select sum() into`在PostgreSQL中将目标变量设置为null
- javascript - 基于 Axios API fetch 的 React 搜索
- sql - SQL查询以获取字符之间的特定字符串
- ios - 如何在带有图像的 SwiftUI 中使用 Bundle
- asp.net-mvc-4 - 代码在 mvc 控制器中执行两次问题
- ios - iOS - 实现自定义集合视图布局