这是我的数据库
"Users" : {
"2rnWA7TF11gSWxec7MsCA5iRhjw1" : {
"favoriteCount" : 1,
"interest" : [ "dogs", "cats", "technology" ],
"speciality" : [ "Swift" ],
},
"3Id9oX0ZOEM00XJlnR07gGrHs762" : {
"favoriteCount" : 7,
"interest" : [ "dogs", "cats", "Asp.NET MVC", "JavaScript" ],
"speciality" : [ "Microsoft Technologys" ],
}
我想在整个数据库中访问用户信息interest = dogs我该怎么办?
答案 0 :(得分:2)
您当前的数据结构可让您轻松查找特定用户的兴趣。但是,它不允许为特定兴趣轻松查找用户。
要允许查找用户的兴趣,您需要为其下的每个用户添加一个反向数据结构/Interests/$interest
和用户ID:
"Interests": {
"dogs": {
"2rnWA7TF11gSWxec7MsCA5iRhjw1": true,
"3Id9oX0ZOEM00XJlnR07gGrHs762": true
},
"cats": {
"2rnWA7TF11gSWxec7MsCA5iRhjw1": true,
"3Id9oX0ZOEM00XJlnR07gGrHs762": true
},
"technology": {
"2rnWA7TF11gSWxec7MsCA5iRhjw1": true,
}
...
}
另见:
答案 1 :(得分:0)
您可以在Firebase中进行查询:
Query query = usersDB.orderByChild("interest").equalTo("WHATEVERINTEREST");
query.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
Users user = dataSnapshot.getValue(Users.class);
doWhatever();
}
});
但是,在您将信息存储为数组的情况下,您可以检索所有用户,并在代码中获取所需信息。
usersDB.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
ArrayList<Users> listOfUsers = new ArrayList<Users>();
for (DataSnapshot dsp : dataSnapshot.getChildren()) {
Users user = dsp.getValue(Users.class);
listOfUsers.add(user);
}
//Check the Users that contains interest
usersWithInterest(listOfUsers,"dogs");
}
});
实现一个简单的方法,读取所有用户列表并检查对狗有兴趣的用户:
usersWithInterest(listOfUsers, "dogs");