swift - 当child是list时按child查询过滤

标签 swift firebase firebase-realtime-database

当我的数据是列表时,我在弄清楚如何过滤和查询时遇到了一些麻烦。在我当前的数据库模型中,我有对话,然后在每个 UID 下是该对话的参与者。我希望能够查找特定用户参与的所有对话。

database model

我不确定如果没有真正的“ child ”,我将如何编写我的代码

let query = Constants.refs.databaseConvo.queryOrdered(byChild: "").queryEqual(toValue: username)
query.observe(.value, with: { (snapshot) in
    for childSnapshot in snapshot.children {
        print(childSnapshot)
    }
})

最佳答案

由于 Firebase 查询的限制,您需要在数据库中创建一个新集合来跟踪用户参与的所有对话。它的结构应该是这样的:

usersConversations {
    userID1 {
        conversationID1: timestamp (or what ever value you would like, I would recommend a timestamp they joined so you can query the latest conversations, etc.)
        conversationID2: timestamp 
        conversationID3: timestamp
    userID2 {
        conversationID1: timestamp
        conversationID2: timestamp
    } ... and so on
}

每当用户加入或离开对话以及您现有的对话 集合时,您都需要添加和删除此集合。

然后,您可以通过执行以下操作来获取具有 uid userID 的用户参与的所有对话:

databaseRef.child("usersConversations").child(userID).observeSingleEvent(of: .value) (snapshot) in {
    if snapshot.exists() {
         // each snapshot child's key will be a conversationID that they are a part of 

    } else {
         // the user is part of no conversations
    }

}

关于swift - 当child是list时按child查询过滤,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53534788/

相关文章:

angular - firebase.auth().onAuthStateChanged 返回什么?

java - 如何从firebase数据库获取所有子节点?

ios - 由于 Firebase 规则而阻止使用唯一用户名

swift - 如何在 Firebase 中检索 UID 和自动 ID 下的数据 Swift

ios - 滑动手势识别器在 SKScene 中间歇性工作

swift - 将 Swift 2 转换为 Swift 3 后,将类型 'String' 的转换值转换为 'Calendar.Identifier' 错误

android - 在没有互联网的设备上通过 Firebase 隐藏 ProgressDialog

ios - 如何在字段开始编辑时覆盖 UITextField 的呈现

ios - UITableView 中的阴影过多

firebase - 带回发的分析