用户输入带有一些标签的帖子。标签以数组的形式返回,我应该检查标签是否已经存在,并使用tagID将其写入post数据库,以便标签与post相关(见下文)。现在发生的事情只是最后一个tagID被记录到数据库而不是所有这些
for item in tags {
ref.child("tags").observeSingleEventOfType(.Value, withBlock: { snapshot in
if snapshot.childSnapshotForPath(item.lowercaseString).exists() {
let tagKey = snapshot.childSnapshotForPath(item.lowercaseString).value as! String
self.saveTagID(tagKey, postKey: Postkey, UID: userID)
} else {
let tagKey = self.ref.child("tags").childByAutoId().key
let tagUpdate = ["/tags/\(item.lowercaseString)": tagKey]
self.ref.updateChildValues(tagUpdate)
self.saveTagID(tagKey, postKey: Postkey, UID: userID)
}
})
}
func saveTagID(tagID: String, postKey: String, UID: String){
let postTag = [tagID: true]
print("post tag\(postTag)")
ref.updateChildValues(["posts/\(postKey)/tagIDs": postTag,
"user-posts/\(UID)/\(postKey)/tagIDs": postTag])
}
这就是数据库的样子。在tagID中,如果只有一个标签
,则应该只有一个{
"posts": {
"-KNlBs1EC6tkfLA2y4Sc": {
"author": "Michele",
"post": "Hello human",
"tagIDs": {
"-KNlBs76y5I0KDV1OXS_": true
},
"tagNames": "test, hope this works",
"uid": "QGacTE84GBSC7uuN4wemxCdHXWo2"
},
"-KNlCB1CACxXPLpYc5ql": {
"author": "Michele",
"post": "You're my only hope",
"tagIDs": {
"-KNlCB723ScwIhYDuwRn": true
},
"tagNames": "help, Obi wan",
"uid": "QGacTE84GBSC7uuN4wemxCdHXWo2"
}
},
"tags": {
"help": "-KNlCB71o5L2PhdQdl62",
"hope this works": "-KNlBs76y5I0KDV1OXS_",
"obi wan": "-KNlCB723ScwIhYDuwRn",
"test": "-KNlBs7509HQ29waf8Ms"
}
}