【问题标题】:How to retrieve objects from firebase by key value如何通过键值从firebase中检索对象
【发布时间】:2016-06-05 07:43:11
【问题描述】:

我是 firebase 新手,我的 firebase 项目有这样的结构

我想获取所有对象,“Interested”值等于“men”

我写了这样的代码,让所有对象按兴趣值排序:

let thisUserRef = URL_BASE.childByAppendingPath("profile")

thisUserRef.queryOrderedByChild("Interest")
     .observeEventType(.Value, withBlock: { snapshot in

     if let UserInterest = snapshot.value!["Interest"] as? String {    
          print (snapshot.key)  
     }
}

但我收到零。

【问题讨论】:

    标签: ios swift firebase


    【解决方案1】:

    您需要遍历所有键值配置文件

          if let allProfiles = snapshot.value as? [String:AnyObject] {
                for (_,profile) in allProfiles {
                      print(profile);
                      let userInterest = profile["Interest"]
               }
           }
    

    这里 _ 是格式为 KYXA-random string 的键,而 profile 将是该键的元素。

    编辑

    根据docs 查询子值。

    尝试thisUserRef.queryOrderedByChild("Interest").equalTo("men"),然后使用我在答案中指定的内部循环

    【讨论】:

    • 好的,谢谢!但实际上我需要接收满足我的条件 userInterest == "men" 的对象。我试图写 if 语句和 print(profile) 但我得到了 nil
    • 这个答案不起作用。 Snapshot.value 不是字符串,而是字典。此外,OP 想要所有 Interest = men 的用户节点。此外,如果有 10,000 个节点,这可能会使设备的内存不堪重负。最好只通过查询检索感兴趣的节点。
    • 如果你使用普通的.Valueretrieve,它实际上将是一个字符串对象字典——我已经测试过了。虽然您的回答确实解释了查询哪个是正确的。
    • 我的立场是正确的!该代码确实有效,并且可能提供解决方案。这不是“最好”的过程,但知道这一点当然很好!
    • 附带说明,通过以这种方式读取数据,它们被读入字典,字典是无序的,因此您将失去顺序(Firebase 通过 Key 自然排序)。它应该在 snapshot.children 中使用 child 进行迭代
    【解决方案2】:

    这是 Firebase 中的基本查询。 (针对 Swift 3、Firebase 4 更新)

        let profileRef = self.ref.child("profile")
        profileRef.queryOrdered(byChild: "Interest").queryEqual(toValue: "men")
        profileRef.observeSingleEvent(of: .value, with: { snapshot in
    
            for child in snapshot.children {
                let dict = child as! [String: Any]
                let name = dict["Name"] as! String
                print(name)
            }
        })
    

    Firebase 的旧文档确实概述了如何处理查询:在此处查找

    Legacy Firebase Queries

    新的文档很薄。

    哦,只是指出变量; thisUserNode 可能应该是 profileRef,因为这就是您实际查询的内容。

    【讨论】:

    • 我对此有疑问!这段代码有效,如果我想删除这个 child.value["Name],我该怎么做?
    猜你喜欢
    • 1970-01-01
    • 2023-04-04
    • 1970-01-01
    • 1970-01-01
    • 2017-01-21
    • 2022-01-06
    • 1970-01-01
    • 2011-05-14
    • 2015-04-09
    相关资源
    最近更新 更多