问题--->
有没有办法检索密钥为autoID
的节点,可能包含特定密钥。就像下面的JSON结构一样,我在一些powers
内有一个子节点autoID
,并非所有,我只想检索那些有密钥的节点powers
他们不知道相应的value
可能是什么。
在下面两种建议的方法中,哪一种消耗更少的BandWidth ?
我的JSON树
node1
-node12
-autoId1
expo: "5122223333"
users:
-MqrvHRBTRcPzrvAOdkklBzeFW7E2
firstName: "Margery"
lastName: "Lady"
-autoId2
powers: "Triple3"
expo: "2123338983"
users:
-LqrsadaDs12BTRcPzrvABzeFW7E2
firstName: "Tyrion"
lastName: "Imph"
-node21
-autoId3
powers: "Triple"
expo: "5123333"
users:
-MqrvHRBTRcPzrvAOdkklBzeFW7E2
firstName: "Cersie"
lastName: "Lady"
-autoId4
powers: "Quad"
expo: "2128983"
users:
-LqrsadaDs12BTRcPzrvABzeFW7E2
firstName: "Sansa"
lastName: "Lady"
我尝试了什么--->
检索整个node12
,然后检查哪个 autoId 具有特定的key
。例如,让我们说权力:" Triple3"
let prntRef = FIRDatabase.database().reference().child("node1").child("node12")
prntRef.observeSingleEventOfType(.Value, withBlock: {(snap) in
if snap.exists(){
for each in snap.value as! [String:AnyObject]{
prntRef.child(each.0 as! String).child("powers").observeSingleEventOfType(.Value, withBlock: {(IMsnap) in
if IMsnap.exists(){
//Found The correct node
}
})
}
}else{
//
}
})
我的另一种替代解决方案是: -
FIRDatabase.database().reference().child("node1").child("node12").queryOrderedByChild("powers").observeSingleEventOfType(.Value, withBlock: {(snap) in
if let snapDict = snap.value! as? [String : AnyObject]{
print(snapDict.keys.first!) //Retrieving My AutoID .Nut this gives me entire node.
}
for each in snap.value as! [String:AnyObject]{
print(each.0) //Retrieving My AutoID
}
})
})
注意: - 我在Firebase论坛上发现了一些类似的Q,但似乎没有人回答: - https://groups.google.com/forum/#!topic/firebase-talk/ZDHKwxRMiKQ
答案 0 :(得分:2)
如果您不关心powers
的值,您只关心autoId节点下的密钥,您只需要.queryEqualToValue("")
(这取决于键值对是一个字符串,对于一个数字,而不是""只需使用0 [取决于你的值大于或等于0]。
let ref = FIRDatabase.database().referenceWithPath("node1/node12")
ref.queryOrderedByChild("powers")
ref.queryEqualToValue("")
ref.observeEventOfType(.Value, withBlock: { snap in
print(snap) // all the autoId nodes that have the powers key
})