ios - 包含在对 Firebase 的查询中

标签 ios swift firebase

来自 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/

相关文章:

android - 将符号上传到 Firebase Crashlytics 时出错

ios - 在点击返回之前运行一个函数。 iOS, swift ,

ios - Collection View - 气泡边框和填充颜色更改为不同颜色

ios - 我可以用 "do not backup"属性标记文档目录吗?

ios - 无法将类型 'UserFile' 的值转换为预期参数 'User'

swift - 存储在 Firestore 中的系统日期对象的行为将发生变化,您的应用程序可能会崩溃?

ios - Swift - 如何检查 var 是否为 nil?

ios - 如何将数据传递给另一个 View

ios - UIButton 背景图片可以支持 Dynamic Type 吗?

firebase - 合并不同服务的 GoogleService-Info.plist 文件