【问题标题】:Firebase: Filtering nested queries is not workingFirebase:过滤嵌套查询不起作用
【发布时间】:2017-08-24 02:52:02
【问题描述】:

我正在尝试在 Firebase 上执行与联接查询等效的 SQL,但我希望它仅在键 privacy 等于 public 时才加入。

下面的代码没有返回结果。如果我删除 child(key) 那么它工作正常,但它不会加入。我真的很想得到一些帮助。

circleQuery?.observe(.keyEntered, with: { (key: String!, location: CLLocation!) in

    self.locationRef.child(key).queryOrdered(byChild: "privacy").queryEqual(toValue : "public").observeSingleEvent(of: .value, with: { (locationSnapshot) in
        if !locationSnapshot.exists() { return }

        // returns no results
    }) { (error) in
        print(error.localizedDescription)
    }

})

【问题讨论】:

  • 你想在 FirebaseDb 中查询并得到结果?
  • 是的。据我了解,要执行连接语句的 SQL 等效项,我应该将两个表的键设置为等效,我已经这样做了。这里的不同之处在于我想让第二个查询有条件,即如果隐私设置为公开。这有意义吗?

标签: swift firebase firebase-realtime-database geofire


【解决方案1】:

在firebase中使用以下方法发布并获取基于查询的结果

   let databaseReff = Database.database().reference().child("your parent node in which query will be searched and compared")

                databaseReff.queryOrdered(byChild: "fromId // parameter whose value will be checked").queryEqual(toValue: self.requiredID //Parameter which will be compared).observe(.value, with: { snapshot in
                    if snapshot.exists(){

                        print(snapshot.value!) //print full snapshot
                        if let snapDict:[String:AnyObject] = snapshot.value as? [String : AnyObject] {

                            let dictKeys = [String](snapDict.keys)
                            print(dictKeys) //print all the nodes that will satisfy your query

                        }

                    }


                })

【讨论】:

  • 对,但是我正在执行两个嵌套查询,第二个查询取决于第一个查询的键。哦,第二个查询不是数组,而只是一个元素。
  • 是的,您也可以这样做,但根据它会很耗时,因为您将一次又一次地访问服务器,因此最好根据一个查询获取快照,然后在[string: anyobject] dict 并根据要求对其进行排序,它将比第一种方法更快地加载您的数据
  • 我之前在查询中使用了 usd 查询,但我使用第二种方法对来自一个查询的数据进行排序。希望有帮助
  • 如果您需要在查询中进行查询,我可以在测试其工作后发布代码?
  • 那真的很有帮助。 TBH 我对结合这两个模型有点矛盾。我已经读过,在 SQL 中将嵌套保持在最低限度是一种很好的做法,因为它会在每次查询时将更少的数据加载到内存中。
最近更新 更多