当子节点的父节点未知时从Firebase检索数据 [英] Retrieving data from Firebase when the parent of the child node is unknown

查看:151
本文介绍了当子节点的父节点未知时从Firebase检索数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在构建一个应用程序,您可以发送并获取朋友请求。该数据库的结构如下:

I am building an app where you can send and get friend request. The database is structured as:

现在我想建立一个警报功能,当有人向你发送一个带有addValueEventListener的朋友请求时,我可以看到当前用户是否有收到数据库。
类似于:

Now I want to build an "alert function" when someone sends you a friend request with an addValueEventListener so that I can see if the current user have a "recieved" in the database. Something like:

mFriendRequestDatabase = 
FirebaseDatabase.getInstance().getReference().child("Friend_req");
    mCurrent_user = FirebaseAuth.getInstance().getCurrentUser();
    String current_user_id = mCurrent_user.getUid();
    mFriendRequestDatabase.child(current_user_id).addValueEventListener(new 
ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {


        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });

问题是我无法看到当前用户是否有已发送或收到,因为我不知道发送请求的人的ID。
dataSnapshot.child(???)。child(sent或recieved)

The problem is that i can't reach to see if current user have a "sent" or a "recieved" since i don't know the ID of the person that sent the request. dataSnapshot.child(???).child("sent" or "recieved")

如何解决这个问题?

推荐答案

你可以通过查询得到一些这样的信息,但是要保持性能得到控制是很棘手的。我需要为每个用户定义一个索引。对于一些问题,请参阅我的答案这里,并此处

You could get some of this with a query, but it'll be tricky to keep the performance under control since you'll need to define an index on every user. For some of the problems with this see my answers here, and here.

更好的方法是将请求分成两个单独的列表:已发送的列表和已接收的列表。例如

A better way is to separate the requests into two separate lists: the ones that were sent, and the ones that were received. E.g.

friend_requests
  uidOfChristoffer
    received
      uidOfPuf: true
    sent:
      uidOfSomeoneElse: true
 uidOfPuf
    sent
      uidOfChristoffer: true
 uidOfSomeoneElse
    received
      uidOfChristoffer: true

现在你可以通过阅读 / friend_requests / theirUid / received 。这是多对多关系的一种更具体的方法,所以我也建议阅读我的答案这里

Now you can specifically get the ones that anyone has received by reading /friend_requests/theirUid/received. This is a more specific approach of a many-to-many relationship, so I also recommend reading my answer on that here.

这篇关于当子节点的父节点未知时从Firebase检索数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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