英文:
Check for a value in many child nodes in firebase real-time database
问题
我想从子节点 'group' 中检索文本 'Private Group',如果子节点 'contacts' 具有值 '9aIMkiMa0bSuMLjUk3R5bLpnoQS2'。我还想从父子节点 'questions posts' 的其他子节点中检查相同的值。我一直在努力,但毫无结果。这是我一直在使用的代码,但它只产生了错误。
final DatabaseReference groupsRef = FirebaseDatabase.getInstance().getReference().child("questions posts");
Query query = groupsRef.orderByChild("group").orderByChild("contacts");
query.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot snapshot) {
arrayList.clear();
if (snapshot.exists() && snapshot.hasChild(onlineUserId)){
arrayList.add(groupsRef.getKey().toString());
arrayAdapter.notifyDataSetChanged();
}
}
@Override
public void onCancelled(@NonNull DatabaseError error) {
}
});
英文:
I want to retrieve the text 'Private Group' from the child 'group' IF the child 'contacts' has the value '9aIMkiMa0bSuMLjUk3R5bLpnoQS2'. I also want to check for the same value from the other child nodes of the parent child 'questions posts'. I have struggled with it but in vain. This is the code that I have been using, but It has only produced errors.
final DatabaseReference groupsRef = FirebaseDatabase.getInstance().getReference().child("questions posts");
Query query = groupsRef.orderByChild("group").orderByChild("contacts");
query.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot snapshot) {
arrayList.clear();
if (snapshot.exists() && snapshot.hasChild(onlineUserId)){
arrayList.add(groupsRef.getKey().toString());
arrayAdapter.notifyDataSetChanged();
}
}
@Override
public void onCancelled(@NonNull DatabaseError error) {
}
});
答案1
得分: 1
一个 Firebase 查询操作在一个扁平节点列表上进行,只能包含一个未知键。
从我所了解的情况来看,你至少有两个层级的未知键(-MH...Ez12
和 9alMk....QS2
),可能还有三个层级(Private Group
)。无法使用数据库查询来查询这种结构,你需要想出一个不同的数据结构来适应你的用例。
例如,如果你想要允许根据给定的联系人 ID 查找帖子,考虑存储确切的关系:
"contactsToPosts": {
"$contactId": {
"$postId": true
}
}
关于这种排序数据建模权衡的更多信息,请参见:
- https://stackoverflow.com/questions/27207059/firebase-query-double-nested
- https://stackoverflow.com/questions/40656589/firebase-query-if-child-of-child-contains-a-value
英文:
A Firebase query operates on a flat list of nodes, and can only contain a single unknown key.
From what I can tell you have at least two levels of unknown keys (-MH...Ez12
, and 9alMk....QS2
) and possibly three (Private Group
). There is no way to query this structure with a database query, and you will need to come up with a different data structure to allow your use-case.
For example, if you want to allow finding the posts for a given contact ID, consider storing exactly that relationship:
"contactsToPosts": {
"$contactId": {
"$postId": true
}
}
For more on this sort data modeling trade-off, see:
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论