来自 Parse,我非常依赖 containedIn
查询来收集正确的数据。在 Parse 中,我可能有一个 objectIds
数组并查询具有这些 ID 的所有对象。我希望在 Firebase 上实现同样的目标。
我知道扁平化数据很重要,但我看不出这对解决问题有何帮助。假设我有一个聊天室,里面有一个用户列表。我收集了这些数据,现在有了一组用户名。我现在想导航到数据库中的用户,并检索与此用户名数组中的一个元素匹配的所有用户。我怎样才能完成这样的事情?
例如Firebase官方例子中的一组用户:
{
"users": {
"alovelace": { ... },
"ghopper": { ... },
"eclarke": { ... }
}
}
我想执行查询以下载以下用户:
["alovelace", "eclarke"]
虽然一般性答案会有所帮助,但 Swift 中的答案最好。谢谢。
最佳答案
An example is that they are the two members of a chat room. Or that the current user is following them.
所以一个理论上的用户节点
users
alovelace
followed_by
bill: true
frank: true
in_chat_room: room_42
location: France
ghopper
followed_by
jay: true
in_chat_room: room_27
location: USA
eclarke
followed_by
frank: true
in_chat_room: room_42
location: Canada
和一些聊天室
chat_rooms
room_27
ghopper: true
room_42
lovelace: true
eclarke: true
获取聊天室42(lovelace,eclarke)用户的详细users节点
let usersRef = self.myRootRef.childByAppendingPath("users")
usersRef.queryOrderedByChild("in_chat_room").queryEqualToValue("room_42")
.observeEventType(.Value, withBlock: { snapshot in
for child in snapshot.children {
let location = child.value["location"] as! String
print(location) //prints France and Canada
}
})
为了获得 Frank 正在关注的用户(lovelace、eclarke):
let usersRef = self.myRootRef.childByAppendingPath("users")
usersRef.queryOrderedByChild("followed_by/frank").queryEqualToValue(true)
.observeEventType(.Value, withBlock: { snapshot in
for child in snapshot.children {
let userName = child.key as String
print(userName)
}
})
请注意,使用用户名作为节点键通常不是一个好主意 - 它们应该按其 uid 存储。
另请注意,我们并没有对 chat_rooms 节点做任何事情,只是为了保持关系,让节点相互引用对于观察变化等很有用。
编辑:
为了回应评论,这里是每个用户显示他们关注的人而不是关注用户的结构
users
alovelace
following_user
bill: true
frank: true
in_chat_room: room_42
location: France
通过这种结构,alovelace 紧随 bill 和 frank。
为了让所有用户都关注 frank:
let usersRef = self.myRootRef.childByAppendingPath("users")
usersRef.queryOrderedByChild("following_user/frank").queryEqualToValue(true)
.observeEventType(.Value, withBlock: { snapshot in
for child in snapshot.children {
let userName = child.key as String
print(userName)
}
})
关于ios - 包含在对 Firebase 的查询中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37551727/