This is a one-to-many relationship: the author has many books.
authors:
randomAuthorId1:
authorId:
authorName:
randomAuthorId2:
authorID:
authorName:
books:
randomAuthorId1:
randomBookId1:
bookId:
bookName:
randomBookId2:
bookId:
bookName:
randomAuthorId2:
randomBookId3:
bookId:
bookName:
In my case, I don't have "randomAuthorId1", but I have "randomBookId2", this is my code to get the value of randomBookId2 node:
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) {
}
});
So he has to iterate over all the children to get a randomBookId2 node. Is there a better way? Thank you all
source
share