2017-08-07 40 views
0

我有一個數據庫方案,它在本質上是相同的是,一個是documentation如何獲得孩子的,其陣列中含有一定值

// An index to track Ada's memberships 
{ 
    "users": { 
    "alovelace": { 
     "name": "Ada Lovelace", 
     // Index Ada's groups in her profile 
     "groups": { 
     // the value here doesn't matter, just that the key exists 
     "techpioneers": true, 
     "womentechmakers": true 
     } 
    }, 
    ... 
    }, 
    "groups": { 
    "techpioneers": { 
     "name": "Historical Tech Pioneers", 
     "members": { 
     "alovelace": true, 
     "ghopper": true, 
     "eclarke": true 
     } 
    }, 
    ... 
    } 
} 

我想創建一個DatabaseQuery即得到所有用戶參加特定組(例如,其「組」包含「techpionneers」的用戶)

我應該如何繼續?我嘗試了Database.database().reference(withPath: "users").queryOrdered(byChild: "groups").queryEqual(toValue: "techpioneers"),但這並不奏效(顯然)。

回答

1

弗蘭克斯解決方案是現貨,但替代方案是使用Deep Query,即按深度路徑排序,以查詢用戶節點是否符合條件的子節點。這裏的格式

let ref = self.ref.child("users") 
    let query = ref.queryOrdered(byChild: "groups/techpioneers").queryEqual(toValue: true) 
    query.observeSingleEvent(of: .value, with: { (snapshot) in 
     for child in snapshot.children { 
      let snap = child as! DataSnapshot 
      print(snap) 
     } 
    }) 

結果是所有可在techpioneers組

"alovelace": { 
    "name": "Ada Lovelace", 
    "groups": { 
     "techpioneers": true, 
     "womentechmakers": true 
     } 
} 
+0

這是一個很好的答案,這樣我就不必做兩個查詢的一部分用戶。謝謝 –

3

,以便加載特定組的所有用戶,開始/groups節點找到自己的關鍵:

ref.child("groups/techpioneers/members").observeSingleEvent(of: .value, with: { (snapshot) in 

這就給了你所有成員的鑰匙。然後循環這些鍵並加載相應的用戶。

這實質上是一個客戶端連接操作。儘管您最初可能認爲這非常慢,但實際上並非如此糟糕,因爲Firebase通過單個連接管理請求。見http://stackoverflow.com/questions/35931526/speed-up-fetching-posts-for-my-social-network-app-by-using-query-instead-of-obse/35932786#35932786

相關問題