【问题标题】:Firebase Realtime Database comparing value inside the child notes with another child noteFirebase 实时数据库将子笔记中的值与另一个子笔记进行比较
【发布时间】:2020-10-17 22:59:11
【问题描述】:

我有一个类似这样的数据库。我想如何比较所有用户的价值以获得最大价值。

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);
    });

【问题讨论】:

  • 您是想在 recyclerview 之类的地方显示您的数据集,还是只想获得最高价格的状态?
  • 我只想获得最高价状态@50_Seconds_Of_Coding
  • 您的编辑使这个问题完全不同,因为它不再与 Android 有关。这意味着现在两个现有答案对这个问题都没有意义。
  • 从您对我的回答的评论看来,您在 Cloud Functions 代码中遇到了错误。请编辑您的问题以包含完整的错误和堆栈跟踪。
  • @FrankvanPuffelen nvm,我已经制作了新节点来单独存储它们。谢谢楼主

标签: android firebase firebase-realtime-database google-cloud-functions


【解决方案1】:

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

另见:

【讨论】:

  • 您好,弗兰克,感谢您的回答,如果使用云功能可以解决这种情况?事件onWrite,之后创建新节点totalPrice/restaurantId/total
  • 如果您的意思是是否可以使用 Cloud Functions 来创建此查询所需的附加数据结构,那么这确实是一种选择。
  • 我已经编辑了这个问题,我确实搜索过这个 stackoverflow.com/a/51436573/9346054 ,但仍然没有工作
【解决方案2】:
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 循环从上面的数据库中迭代并计算您的价格

你可以做的是上传restos的数据时-上传价格时只需为城市总价创建一个额外的节点,并在每次上传新的resto时添加resto的价格

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-09-23
    • 2023-03-04
    • 1970-01-01
    • 2020-05-17
    • 1970-01-01
    • 2019-09-21
    • 2020-03-11
    • 2018-08-28
    相关资源
    最近更新 更多