使用多个查询过滤firebase

问题描述 投票:0回答:2

我有一个数组中的用户列表: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
swift firebase firebase-realtime-database
2个回答
0
投票

在这种情况下,你正在进行'和'查询,根据文档,你应该像这样把多个查询放在一起。

// Create a reference to the cities collection
let commentsRef = db.collection("comments")

// Create a query against the collection.
commentsRef.whereField("postID", isEqualTo: "post1")
commentsRef.whereField("userID", isEqualTo: ['user1', 'user2'])

查看文档以获取更多详细信息。 https://firebase.google.com/docs/firestore/query-data/queries

- -编辑 - -

嗯,如果您更改数据库选择,我将保持高于答案。

我读了这个链接Query based on multiple where clauses in Firebase

所以我认为你应该可以在你的评论模型上添加一个自定义索引

Comments
  -CommentId1
    -postId: "postId1"
    -userId: "UserId1" //RETRIEVE
    -idx: "postID1+UserID1"

现在您可以对此索引执行查询。如果要检索多个用户记录,可以简单地循环用户数组。


0
投票

以下是如何从特定用户检索帖子的两个示例 - 可以通过添加其他if语句来扩展选项以从不需要的用户中排除帖子。

这是Firebase结构

comments
-CommentId1
 -postId: "postId1"
 -userId: "UserId1" //RETRIEVE
-CommentId2
 -postId: "postId2"
 -userId: "UserId50" //DO NOT RETRIEVE

并且代码绑定到UI中的两个不同按钮

var postsArray = [String]()
let userIdWeWant = "userId1"

func button0() {
    self.postsArray = []
    let commentsRef = self.ref.child("comments")
    commentsRef.observe(.childAdded, with: { snapshot in
        let dict = snapshot.value as! [String: Any]
        let userId = dict["userId"] as! String
        if userId == self.userIdWeWant {
            let post = dict["postId"] as! String
            self.postsArray.append(post)
            print(post)
        }
    })
}

func button1() {
    self.postsArray = []
    let commentsRef = self.ref.child("comments")
    commentsRef.observeSingleEvent(of: .value, with: { snapshot in
        for child in snapshot.children {
            let childSnap = child as! DataSnapshot
            let dict = childSnap.value as! [String: Any]
            let userId = dict["userId"] as! String
            if userId == self.userIdWeWant {
                let post = dict["postId"] as! String
                self.postsArray.append(post)
            }
        }
        print(self.postsArray)
    })
}

事实上,我们只是从userId1捕获帖子并将它们添加到一个数组中,但是我们想要从任何喜欢披萨并且鞋子尺寸为13的用户捕获帖子。所以结构将是

comments
    -CommentId1
     -postId: "postId1"
     -userId: "UserId1" //RETRIEVE
     -food: "Pizza"
     -shoe: "13"

和一个代码片段

let shoe = dict["shoe"] as! String
let food = dict["food"] as! String
if shoe == self.shoeWeWant && food == self.foodWeWant {

编辑

根据评论中的一个问题,“将任何uid存储在uid数组中”,它在Swift 4中非常简单。下面是一个示例,看一个对象是否存在于数组中

var uidArray = ["uid0", "uid1", "uid2", "uid3"]
if uidArray.contains("uid1") {
    print("it exists! Do something with it!")
} //otherwise ignore it

该技术可用于查看是否在数组中读取

let userId = dict["userId"] as! String

存在于您感兴趣的用户数组中。

© www.soinside.com 2019 - 2024. All rights reserved.