当我的数据是列表时,我在弄清楚如何过滤和查询时遇到了一些麻烦。在我当前的数据库模型中,我有对话,然后在每个 UID 下是该对话的参与者。我希望能够查找特定用户参与的所有对话。
我不确定如果没有真正的“ 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/