2016-06-16 30 views
2

このFirebase - proper way to structure the DBFirebase - observeEventTypeにキーの値を取得する方法=値

へのフォローアップの質問です私次のDB構造:

"artists" : { 
    "-KKMkpA22PeoHtBAPyKm" : { 
    "name" : "Skillet" 
    } 
} 

をそして、私はアーティストがrefを照会すると、アーティストがすでにDBに入っているかどうかを確認し、アーティストがDBにいる場合は、アーティストキーを取得します(上記の例では-KKMkpA22PeoHtBAPyKm)。

artistsRef.queryOrderedByChild("name").queryEqualToValue("Skillet").observeEventType(.Value, withBlock: { (snapshot) in 
     if snapshot.exists() { 
      print("we have that artist, the id is \(snapshot.key)") 
     } else { 
      print("we don't have that, add it to the DB now") 
     } 
    }) 

が、 "snapshot.keyは" 私だけ "アーティスト" である親キーを与える:

は、私はこれを試してみました。

私は必要な鍵をどのように入手できますか?もし条件で

答えて

4

、あなたは

if snapshot.exists() { 
     for a in (snapshot.value?.allKeys)!{ 
      print(a) 
     } 
    } else { 
     print("we don't have that, add it to the DB now") 
    } 
+0

私のためにはコンパイルされません。代わりに、in(snapshot.value?.allKeys)! { –

+0

@PaulBeusterien ok ..私はこのコードをテストしませんでした。だからそれはそうかもしれません:) –

2

はここソリューションです... allKeysは "-KKMkpA22PeoHtBAPyKm" を取得するために取得する必要があります。

let ref = self.myRootRef.childByAppendingPath("artists") 

ref.queryOrderedByChild("name").queryEqualToValue("Skillet") 
    .observeEventType(.Value, withBlock: { snapshot in 

    if (snapshot.value is NSNull) { 
      print("Skillet was not found") 
    } else { 
      for child in snapshot.children { //in case there are several skillets 
       let key = child.key as String 
       print(key) 
      } 
    } 
}) 
+0

'snapshot.value is NSNull'を'!snapshot.exists() 'に置き換えることができます。 – luckyging3r

関連する問題