我对Firebase有疑问。即将建立排行榜数据库。 所以我的问题是:是否可以先按子“分数”对数据库进行排序,然后遍历此特定顺序并同时更新数据库中子的“排名”?
这是数据库的方案:
https://i.imgur.com/LxRymVx.png
到目前为止找不到任何解决方案。谢谢
答案 0 :(得分:0)
首先,您需要声明数据库引用:
let ref = Database.database().reference(withPath: "Leaderboard")
然后,您需要在此处进行简单查询并访问查询中的元素:
ref.queryOrdered(byChild: "Score").observe(.value, with: { (snapshot) in
for (index, child) in snapshot.children.enumerated {
if let leaderboardSnapshot = child as? DataSnapshot, let leaderBoardValues = leaderboardSnapshot.value as? [String: Any] {
// here you should update your children
let values = ["Name": (leaderBoardValues["Name"] as? String) ?? " ", "Ranking": index, "Score": (leaderBoardValues["Score"] as? Int) ?? 0]
ref.child(leaderboardSnapshot.key).updateChildValues(values, withCompletionBlock: { (error, ref) in
// check for error here if you want
})
}
}
}