如何提取id中特定部分等于某个字符串的Firebase中的所有子代 [英] how to extract all child in firebase with certain part of the id iqual to some string
问题描述
具有此Firebase结构我如何仅检索与该孩子聊天的孩子键几乎具有当前用户ID. 聊天的孩子ID如下 11-126
having this firebase structure how do i retrive only the childs of chats that child key have almost the current user id. the chats child id are like this 11-126
所以说mi用户id我们11.我想用-的任何一边都具有11的所有数据检索所有子项.如果有一个89-11 o 253-11 o 11-254的孩子,我想取回所有这些孩子. 现在,我正在检索所有孩子,并查看密钥是否包含我对此代码感兴趣的ID.
so let say mi user id us 11. i want to retrive all child with all it data that have 11 in any side of - . if there is a child with 89-11 o 253-11 o 11-254 i want to retrive all of those childrens. now i'm retriving all child and watching if key contains the id im interested whit this code.
chatsRef.observe(.childAdded, with: { [weak self] snapshot in
if snapshot.key.contains(String(requestManager.instance.user.id!)){
if let data = snapshot.value as? [String: Any]{
let id = data["id"] as! String
let name = data["name"] as! String
let message = data["body"] as? String
let senderId = data["senderId"] as! String
let url = self?.rootRef.child("user").child(senderId).value(forKey: "url") as? String
}
}
})
转换为字典后,出现错误.
afer the conversion to Dictionary I got an error.
线程1:致命错误:展开包装时意外发现nil 可选值.
Thread 1: Fatal error: Unexpectedly found nil while unwrapping an optional value.
数据值是这个.
似乎是data ["0"].value可以正常工作,但事实并非如此.知道如何提取添加的子项的所有值
seem to be that data["0"].value wourl work but it does not. Any idea how to extract all the values of the child added
推荐答案
听起来您想检索用户11
的所有聊天记录,这意味着senderId
或recipientId
是11
. Firebase实时数据库无法支持这种类型的OR查询,该数据库仅支持对单个属性的查询.
It sounds like you want to retrieve all chats for user 11
, which means that either senderId
or recipientId
is 11
. This type of OR query is not possible with the Firebase Realtime Database, which only supports queries on a single property.
相反,向您的JSON添加一个数据结构,该数据结构包含每个用户ID的聊天室ID.所以:
Instead, add a data structure to your JSON that holds the chat room IDs for each user ID. So:
"userChats": {
"11": {
"11-126": true
}
"126": {
"11-126": true
}
}
使用此附加数据结构,您可以轻松地在/userChats/$uid
下为用户查找聊天室,然后为其加载单个聊天室.
With this additional data structure you can easily look up the chat rooms for a user under /userChats/$uid
and then load the individual chat rooms for them.
这篇关于如何提取id中特定部分等于某个字符串的Firebase中的所有子代的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!