首页 > 解决方案 > 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);
    });

标签: androidfirebasefirebase-realtime-databasegoogle-cloud-functions

解决方案


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"
  }
}

另见:


推荐阅读