简体   繁体   English

当子节点的父节点未知时从Firebase检索数据

[英]Retrieving data from Firebase when the parent of the child node is unknown

I am building an app where you can send and get friend request. 我正在构建一个可以发送和获取朋友请求的应用程序。 The database is structured as: 该数据库的结构为:

链接到图片

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. 现在,当有人向您发送带有addValueEventListener的好友请求时,我想构建一个“警报功能”,以便我可以查看当前用户在数据库中是否有“已接收”消息。 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) {

        }
    });

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. 问题是,由于我不知道发送请求的人的ID,我无法联系到当前用户是“已发送”还是“已接收”。 dataSnapshot.child(???).child("sent" or "recieved") dataSnapshot.child(???)。child(“已发送”或“已接收”)

How to I solve this problem? 我该如何解决这个问题?

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. 更好的方法是将请求分为两个单独的列表:已发送的请求和已接收的请求。 Eg 例如

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

Now you can specifically get the ones that anyone has received by reading /friend_requests/theirUid/received . 现在,您可以通过阅读/friend_requests/theirUid/received专门获得任何人都收到的/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 . 这是多对多关系的一种更具体的方法,因此我也建议您在此处阅读我的回答。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM