2017-06-15 506 views
1

的火力點數據結構是加入在火力地堡數據庫

{ 
    "eventAttendees" : { 
    "fm" : { 
     "1" : "David", 
     "2" : "Alice" 

    } 
    }, 
    "events" : { 
    "fm" : { 
     "date" : "2017-06-16", 
     "name" : "Firebase Meetup" 
    }, 
    "gm" : { 
     "date" : "2017-08-12", 
     "name" : "Meet Linh" 
    } 
    }, 
    "users" : { 
    "1" : { 
     "email" : "[email protected]", 
     "name" : "David" 
    }, 
    "2" : { 
     "email" : "[email protected]", 
     "name" : "Alice" 
    }, 
    "10" : { 
     "email" : "[email protected]", 
     "name" : "Khanh" 
    } 
    } 
} 

我想找個誰去調頻事件的所有用戶。這裏是我的代碼:

let ref = Database.database().reference() 
ref.child("eventAttendees/fm").observe(.value, with: { (snapshot) in 
      print (snapshot.key) 
      ref.child("users/\(snapshot.key)").observeSingleEvent(of: .value, with: { (userSnapshot) in 
       let content = userSnapshot.value as? [String : AnyObject] ?? [:] 
       print(content) 
      }) 
     }) 

我按照這個教程https://youtu.be/Idu9EJPSxiY?t=3m14s

底座上的教程snapshot.key應該返回 「1」, 「2」,使ref.child("users/\(snapshot.key)")ref.child("users/1")

但在我代碼,snapshot.key返回「fm」和ref.child("users/\(snapshot.key)")將是ref.child("users/fm")

我的代碼中的問題在哪裏?

回答

3

根據eventAttendees/fm你有多個孩子。因此,您需要循環代碼中的這些子節點:

let ref = Database.database().reference() 
ref.child("eventAttendees/fm").observe(.value, with: { (snapshot) in 
    for child in snapshot.children.allObjects as [FIRDataSnapshot] { 
     print (child.key) 
     ref.child("users/\(child.key)").observeSingleEvent(of: .value, with: { (userSnapshot) in 
      let content = userSnapshot.value as? [String : AnyObject] ?? [:] 
      print(content["name"]) 
     }) 
    } 
}) 
+0

謝謝!奇怪的是,在視頻教程中,作者不必循環。我錯過了什麼? – John

+1

在視頻中,David使用on(「child_added」作爲外部循環,爲每個孩子啓動一個單獨的事件,使用'on(「value」',它爲所有匹配的孩子啓動一個事件,這意味着你需要在回調函數中循環。 –