【问题标题】:Firebase query results are mistakenFirebase 查询结果有误
【发布时间】:2018-11-10 15:46:16
【问题描述】:

这是我的数据库设计。

foodie-ab2b4{
 Foods{
   0{
    FoodName: "Baked Beans In Tomato Sauce"
    FoodRecipe: 
    FoodUri: 
    Image: 
    }
   1{
    FoodName: "Another bean | Bubbling Bacon Butter Beans recipes"
    FoodRecipe: 
    FoodUri: 
    Image: 
    }
   }
  }

我正在开发一个 ios 项目,这就是我的 firebase json 的结构。

let ref = Database.database().reference()
func searchFoodByName(FoodName: String){
    let foodsRef = ref.child("Foods")

    let input = FoodName
    let query = foodsRef.child(key).queryOrdered(byChild: "FoodName").queryEnding(atValue: input)
    query.observeSingleEvent(of: .value, with: { snapshot in
        print(snapshot)
        for child in snapshot.children {
            let snap = child as! DataSnapshot
            let dict = snap.value as! [String: Any]
            let fName = dict["FoodName"] as! String
            let fIngredients = dict["Ingredients"] as! [String]
            print(fName)
            print(fIngredients)

            let key = snapshot.key
            print(key)
        }
    })    
}

我正在尝试按名称过滤我的食物对象。我的数据库中有 10 个对象。在大多数情况下,此搜索返回真实对象。但是有一个例子我解决不了。

当我查询“番茄”这个词时,我需要得到 1 个对象。但是有两个。虽然我的第二个对象中没有番茄字。

这两个对象在我的 json 文件中。

如果有必要,我可以将我的整个 JSON 文件上传到这里。

【问题讨论】:

  • key的值是多少?

标签: ios swift firebase firebase-realtime-database


【解决方案1】:

您似乎认为 Firebase 可以根据 包含 值的字符串进行过滤,但事实并非如此。请参阅Firebase query - Find item with child that contains string(以及那里的许多链接)。

Firebase可以做的是搜索某个值开始的字符串值。您可以通过使用 queryStarting(atValue:)queryEnding(atValue:) 的组合来做到这一点:

let query = foodsRef
  .queryOrdered(byChild: "FoodName")
  .queryStarting(atValue: input)
  .queryEnding(atValue: input+"\\uf8ff")

如果您使用此查询,并且input 是“Baked”,它将仅匹配您 JSON 中的第一个食物。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-18
    • 1970-01-01
    • 2021-10-28
    • 2018-08-27
    • 2018-12-06
    相关资源
    最近更新 更多