我有一个关于firebase的后端,有像Facebook这样的帖子.所以我需要喜欢这些帖子的功能.问题是如何存储喜欢帖子的喜欢和用户?
所有帮助将不胜感激
所有帮助将不胜感激
解决方法
采用这种数据结构:
{
"posts": {
"post_1": {
"uid": "user_1","title": "Cool Post"
},"post_2": {
"uid": "user_1","title": "Another Cool Post"
},"post_3": {
"uid": "user_2","title": "My Cool Post"
}
},"postLikes": {
"user_1": {
"post_3": true
},"user_2": {
"post_1": true,"post_2": true
}
}
}
位置/帖子检索所有帖子.
location / postLikes检索帖子上的所有喜欢.
所以,假设您是user_1.要获取user_1喜欢的帖子,您可以编写此Firebase数据库侦听器:
let ref = Firebase(url: "<my-firebase-app>")
let uid = "user_1"
let userRef = ref.childByAppendingPath(uid)
userRef.observeEventType(.Value) { (snap: FDataSnapshot!) in
print(snap.value) // prints all of the likes
// loop through each like
for child in snap.children {
let childSnap = child as! FDataSnapshot
print(childSnap.value) // print a single like
}
}
这里需要注意的重要一点是数据结构的“平坦性”. postLikes不存储在每个帖子下.这意味着您可以在不获取所有喜欢的情况下检索帖子.但是,如果你想同时获得两者,你仍然可以这样做,因为你知道用户的id.
Try giving the Firebase guide on Structuring Data a read through