在firebase中使用随机密钥获取子节点数据的最佳方法是什么?

时间:2018-04-12 04:26:23

标签: java android json firebase firebase-realtime-database

这是一对多关系:作者有很多书

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的节点。有没有更好的办法? 谢谢大家

2 个答案:

答案 0 :(得分:3)

您可以使用查询来执行此操作,但使用查询需要更新您的图书数据库,如下所示 书籍:

randomAuthorId1:  
   randomBookId1:
        bookId:  
        randomBookId:randomBookId1
        bookName:
   randomBookId2:
        bookId:
        randomBookId:randomBookId2
        bookName:
randomAuthorId2:
    randomBookId3:
        bookId:
        randomBookId:randomBookId3
        bookName:

此后,您可以像bellow

一样触发查询
Query queryToGetData = databaseReference.child("books")
        .orderByChild("randomBookId").equalTo("randomBookId2");
queryToGetData.addChildEventListener(new ChildEventListener() {
    // TODO: 
    // ...
});

它会帮助你。

答案 1 :(得分:1)

如果您知道要获取哪个值的子名称,则无需在eventlistener中调用hasChild。而只需要引用特定的子项并将其放入try catch中。因此,如果找不到孩子,那么您可以捕获异常并按照自己的意愿执行操作。

示例代码:

try
{
    DatabaseReference bookRef = FirebaseDatabase.getInstance().getReference("books").child("randomBookId2");
    //add valueevent listener for this reference...
}catch(Exception e){
    //Child not found...perform action according this.
}