Firebase:查询以根据条件排除数据 [英] Firebase: Query to exclude data based on a condition

查看:22
本文介绍了Firebase:查询以根据条件排除数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以使用 orderByChildequalTo 获取子节点中特定值的数据(很酷,它也适用于嵌套子节点)

I'm able to get the data for a particular value in the child using orderByChild and equalTo (cool that it works for nested child as well)

private void getData() {
        try {
            final DatabaseReference database = FirebaseDatabase.getInstance().getReference();

            database.child(Constants.TABLE_TASKS).orderByChild("user/id")
                    .equalTo("somevalue")
                    .addValueEventListener(new ValueEventListener() {
                        @Override
                        public void onDataChange(DataSnapshot dataSnapshot) {
                            Timber.d(dataSnapshot.toString());
                        }

                        @Override
                        public void onCancelled(DatabaseError databaseError) {
                        }
                    });
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

是否有一种简单的方法可以在找不到特定值的情况下获取数据,基本上类似于 notEqualTo("somevalue") ?

Is there an easy way to get the data where a particular value is not found, basically something like a notEqualTo("somevalue") ?

推荐答案

我想我已经找到了解决方案,这更多的是应该如何设计数据库,实际上现在我理解了 Firebase 指南背后的意图

I think I've found the solution and this is more of how the database should be designed and actually now I understood the intention behind Firebase guideline

https://firebase.google.com/docs/database/android/结构数据

原创设计:

{
    child1: {
      "user": {
        "id": "id1",
        "name": "puf"
      }
    },
    child2: {
      "user": {
        "id": "id2",
        "name": "abe"
      }
    },
    child3: {
      "user": {
        "id": "id1"
        "name": "puf"
      }
    }
}

更新设计:

所以除了存储用户的id和name之外,我们还应该存储一个以id本身为key的节点,并标记为true

So apart from the storing the id and name of the user, we should also store a node with the id itself as the key and mark it to true

{
    child1: {
      "user": {
        "id": "id1",
        "name": "puf"
        "id1": true
      }
    },
    child2: {
      "user": {
        "id": "id2",
        "name": "abe"
        "id2": true
      }
    },
    child3: {
      "user": {
        "id": "id1"
        "name": "puf"
        "id1": true
      }
    }
}

使用更新的设计,如果我执行 ref.orderByChild('user/id1').equalTo(true)

With the updated design, if i execute ref.orderByChild('user/id1').equalTo(true)

我会得到 Child1 和 Child 3 的输出

I would get output as Child1 and Child 3

如果我执行 ref.orderByChild('user/id1').equalTo(null),

我会得到 Child2 作为输出

I would get Child2 as the output

这篇关于Firebase:查询以根据条件排除数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆