我对使用Firebase还很陌生,我正努力只访问父密钥来删除该值。
我正在尝试使用以下代码访问父密钥:
if let exerciseName = exercises[indexPath.row].exerciseName {
let ref = FIRDatabase.database().reference().child("userExercises")
ref.queryOrdered(byChild: "exerciseName").queryEqual(toValue: exerciseName).observe(.childAdded, with: { (snapshot) in
print(snapshot.ref)
})
}
我的数据结构如下:
.
但是当我打印出值时,如果数据库中有另一个用户具有相同的
exerciseName
,它会打印出所有父键。如何才能只删除选定要删除的记录?
当我
print(snapshot)
时,结果是:Snap (-KWw9hg2Uiyo9_cj7TAy) {
bodyPart = Back;
exerciseName = "Test 2";
userId = 8rHmyTxdocTEvk1ERiiavjMUYyD3;
}
Snap (-KWwAGd3t9vsW0LHKtV1) {
bodyPart = Arms;
exerciseName = "Test 2";
userId = PO8p0UoqqHOas3D9Ise8CgWT3PN2;
}
最佳答案
尝试:
let ref = FIRDatabase.database().reference().child("userExercises")
let filteredRef = // do some query,sorting ...
filteredRef.observe(.value, with: { snapshot in
for item in snapshot.children {
guard let itemSnapshot = item as? FIRDataSnapshot else { break }
guard let dict = itemSnapshot.value as? NSDictionary else { break }
let id = itemSnapshot.key // this is the record id of an exercise !
}
}
要删除其中一个记录:
let ref = FIRDatabase.database().reference().child("userExcercises").child(record_id) // see above how to fetch the id
ref.removeValue()
我建议你重组你的用户练习,比如:
{
"userExcercises" : {
"<USER-ID>" : {
"<EXCERCISE-ID>" : {
"bodyPart" : "Back",
"excerciseName" : "Test02"
},
// lots of more excercises for this user ...
},
// lots of more users ...
}
}
要清楚:USER-ID是经过身份验证的用户的uid,exercise-ID是自动生成的(childByAutoId())ID