首页 文章

Firebase复杂查询 - iOS Swift

提问于
浏览
0

我有像应用程序的Instagram . 我有firebase作为后端,它有:

post node - 包含来自不同用户的所有帖子[post_id post_user post_name post_content]

Problem: 我想只收听我所关注的用户的帖子 .

My Steps:

  • 我在数组中得到了以下users_id的列表
followersIds
  • 我想知道我是否可以进行查询
getFollowersList { (followersIds) in

    print(followersIds)

    self.postRef.queryOrdered(byChild: "user").queryEqual(toValue: followersIds).queryLimited(toLast: limit).observeSingleEvent(of: .value, with: { (snapshot) in
        if snapshot.value is NSNull { completion(nil); return}
        else {
            let dict = snapshot.value as! [String:Any]
            self.mapDictionaryToArrayOfPost(dict: dict, completion: { (posts) in
                completion(posts)
            })
        }
    }) { (error) in
        debugPrint(error.localizedDescription)
    }

}

ISSUE: Firebase无法在queryEqual()中接受数组作为参数

我可以通过在应用程序中过滤来执行此过滤器,但我想查询firebase并获取结果 . 因为在应用程序中进行过滤并不是一件好事 .

任何建议 .

1 回答

  • 2

    在Firebase中无法一次性执行此查询 . 在大多数NoSQL解决方案中很常见,您应该以允许应用程序需要的用例的方式对数据建模 .

    这意味着:如果您想要一次性检索您关注的人的所有帖子,您应该保留您在数据库中关注的所有帖子的列表 . 由于您似乎正在构建类似社交网络的东西,这意味着您实际上构建了每个用户的墙:

    following
      uid1
        uid2: true // so uid1 follows uid2 and uid3
        uid3: true
      uid3
        uid2: true // and uid3 follows uid2
    posts
        post1 
          author: uid2 // uid2 has made a post
          title: "...." 
        post2 
          author: uid3 // uid3 has made a post
          title: "...." 
    wall
      uid1
        post1: true
        post2: true
      uid3
        post1: true
    

    因此,在此模型中,我们会保留您在 /wall/myuid 下关注的用户的每个帖子的关键字 . 现在,您可以轻松获取帖子列表以显示特定用户的墙 . 从那里你可以循环键并加载每个键 . 后者在Firebase上运行速度不慢,因为它会对请求进行管道传输 . 见Speed up fetching posts for my social network app by using query instead of observing a single event repeatedly .

    这种类型的数据复制在NoSQL数据库(例如Firebase)中非常常见,这就是为什么我们在documentation on structuring datafirefeed demo app和我们的新视频系列_2882659中覆盖它 .

相关问题