【问题标题】:Firebase complex query - iOS SwiftFirebase 复杂查询 - iOS Swift
【发布时间】:2016-11-29 04:33:53
【问题描述】:

我有 Instagram 之类的应用。 我有firebase作为后端:

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

问题: 我只想从我关注的用户那里获取帖子。

我的步骤:

  1. 我在数组中得到了以下 users_id 的列表

    followersIds
    
  2. 我想知道我是否可以像这样查询

    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)
        }
    
    }
    

问题: Firebase 不能接受数组作为 queryEqual() 中的参数

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

任何建议。

【问题讨论】:

    标签: ios swift firebase firebase-realtime-database


    【解决方案1】:

    无法在 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

    这种类型的数据重复在 Firebase 等 NoSQL 数据库中非常常见,这就是我们在 documentation on structuring datafirefeed demo app 和我们的新视频系列 Firebase for SQL developers 中介绍它的原因。

    【讨论】:

      猜你喜欢
      • 2021-09-01
      • 1970-01-01
      • 1970-01-01
      • 2016-10-15
      • 2021-10-22
      • 1970-01-01
      • 2019-10-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多