作者:财珍文纶1 | 来源:互联网 | 2023-08-21 10:55
这是一对多的关系:作者有很多书
authors:
randomAuthorId1:
authorId:
authorName:
randomAuthorId2:
authorID:
authorName:
books:
randomAuthorId1:
randomBookId1:
bookId:
bookName:
randomBookId2:
bookId:
bookName:
randomAuthorId2:
randomBookId3:
bookId:
bookName:
在我的情况下,我没有“randomAuthorId1”,但我有“randomBookId2”,这是我获取randomBookId2节点值的代码:
DatabaseReference bookRef = FirebaseDatabase.getInstance().getReference("books");
bookRef.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot data : dataSnapshot.getChildren()) {
if (data.hasChild("randomBookId2")) {Book book = data.child("randomBookId2").getValue(Book.class);
}
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
因此,它必须遍历所有子节点才能获得randomBookId2的节点.有没有更好的办法?
谢谢大家
解决方法:
您可以使用Query执行此操作,但使用查询需要更新您的Books DB,如下所示.
图书:
randomAuthorId1:
randomBookId1:
bookId:
randomBookId:randomBookId1
bookName:
randomBookId2:
bookId:
randomBookId:randomBookId2
bookName:
randomAuthorId2:
randomBookId3:
bookId:
randomBookId:randomBookId3
bookName:
此后,您可以像下面一样触发查询
Query queryToGetData = databaseReference.child("books")
.orderByChild("randomBookId").equalTo("randomBookId2");
queryToGetData.addChildEventListener(new ChildEventListener() {
// TODO:
// ...
});
它会对你有所帮助.