【问题标题】:Firebase - Retrieving Node using 'Node-Id'Firebase - 使用“节点 ID”检索节点
【发布时间】:2016-05-25 21:06:23
【问题描述】:

在检索完整节点时,我很难理解如何使用 where。如果我有这样的结构:

- users
   -user_id1
      - key1:value1
      - key2:value2
   -user_id2
      - key1:value3
      - key2:value4
  ...

如果我知道“user_id1”,如何获取整个节点;所以我可以使用snapshot.key获取user_id,使用snapshot.value获取[key:value]

   -user_id1
      - key1:value1
      - key2:value2

这是我迄今为止尝试过的......

let key = "user_id1"   // static for test

let usersRef = Firebase(url: secret + "/users")
usersRef.queryEqualToValue(key).observeSingleEventOfType(.Value, withBlock: { snapshot in

       print(snapshot)

//     print(snapshot.key)   // id
//     print(snapshot.value) // [key:value]                  
})

这是返回:

Snap (users) <null>

Snap (users) <null>

【问题讨论】:

    标签: ios swift firebase firebase-realtime-database


    【解决方案1】:

    这比您尝试的要简单得多:

    ref.child("users").child("user_id1").observeSingleEventOfType(.Value, withBlock: { snapshot in
        print(item.key)
        print(item.value)
    })
    

    这不仅更简单,而且对数据库来说也更便宜,因为它不必执行(可能很昂贵的)查询。

    例如,请参阅documentation on reading child value with Swift 的这一部分。

    【讨论】:

    • @Frank van Puffelen 我在测试中一直在使用这两种方法,但不确定何时应该使用这种直接引用与查询方法。您对何时使用其中一个或另一个有任何 cmet 吗?
    • 是的。你的也可以。但如果你有机会,用一个简单的child() 调用替换它,它会扩展得更好。
    • 感谢 Puff - 也更干净了。
    【解决方案2】:

    尝试添加queryOrderedByKey()

    例如

    let ref = root.child("users")
    
    ref.queryOrderedByKey().queryEqualToValue("user_id1").observeSingleEventOfType(.Value, withBlock: { snapshot in
    
        // could get many items in snapshot hence the loop
    
        for item in snapshot.children {
            print(item)
        }
    
    })
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多