我对使用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;
}
答案 0 :(得分:3)
尝试:
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:
{
"userExcercises" : {
"<USER-ID>" : {
"<EXCERCISE-ID>" : {
"bodyPart" : "Back",
"excerciseName" : "Test02"
},
// lots of more excercises for this user ...
},
// lots of more users ...
}
}
要明确:USER-ID是经过身份验证的用户的uid,EXCERCISE-ID是自动生成的(childByAutoId())id