我有一个数组中的用户列表:let userArray = [“userId1”,“userId2”] . 我正在尝试为给定的postId提取所有注释的列表,并过滤结果以仅拉取userId在userArray中的那些 . 下面是我的代码到目前为止,但它似乎没有工作 . 有没有更好的方法来解决这个问题?
//pulls all comments given a postId of "postId1"
let commentsRef = databaseRef.child("comments").queryOrdered(byChild: "postId").queryEqual(toValue: "postId1")
commentsRef.observe(.value, with: { (comments) in
var resultArray = [Comment]()
for comment in comments.children {
let value = child.value as? NSDictionary
let userId = value?["userId"] as? String ?? ""
for contactinfo in userArray {
if(contactinfo = userId) {
let comment = Comment(snapshot: comment as! DataSnapshot)
resultArray.append(comment)
}
}
completion(resultArray)
}
})
})
火力地堡:
Comments
-CommentId1
-postId: "postId1"
-userId: "UserId1" //RETRIEVE
-CommentId2
-postId: "postId2"
-userId: "UserId50" //DO NOT RETRIEVE
2 回答
在这种情况下,你正在进行'和'查询,根据文档,你应该像这样把多个查询放在一起 .
查看文档以获取更多详细信息 . https://firebase.google.com/docs/firestore/query-data/queries .
嗯,如果您更改数据库选择,我将保持高于答案 .
我读了这个链接Query based on multiple where clauses in Firebase .
所以我认为你应该可以在你的评论模型上添加一个自定义索引
现在您可以对此索引执行查询 . 如果要检索多个用户记录,可以简单地循环用户数组 .
以下是如何从特定用户检索帖子的两个示例 - 可以通过添加其他if语句来扩展选项以从不需要的用户中排除帖子 .
这是Firebase结构
并且代码绑定到UI中的两个不同按钮
事实上,我们只是从userId1捕获帖子并将它们添加到一个数组中,但是我们想要从任何喜欢披萨并且鞋子尺寸为13的用户捕获帖子 . 所以结构将是
和一个代码片段
EDIT
根据评论中的一个问题,“将任何uid存储在uid数组中”,它在Swift 4中非常简单 . 下面是一个示例,看一个对象是否存在于数组中
该技术可用于查看是否在数组中读取
存在于您感兴趣的用户数组中 .