我想知道是否可以在当前路径的完成块内访问另一条路径。
我使用它的方式如下......我有一个社交媒体应用程序,带有“帖子”路径。这显然是我获得帖子的所有信息的地方。我想为每个帖子创建“评论”。这就是我想要通往“评论”的途径。有人建议实现这一目标是什么?
答案 0 :(得分:2)
以下是它应该如何工作的示例代码。在我的项目中使用相同的方法。当然,路径是假的,所以用你的实际路径填充它。
// Read all posts from Firebase
ref.child("posts").observeEventType(.Value, withBlock: { snapshot in
if let snapshots = snapshot.children.allObjects as? [FIRDataSnapshot] {
// Loop through all posts
for snap in snapshots {
// Read comments for each post. snap.key in code below represents post key. Don't know if you have same structure so fill your data here.
ref.child("comment").child(snap.key).observeEventType(.Value, withBlock: { snapshot in
if let postDictionary = snapshot.value as? Dictionary<String, AnyObject> {
// Here you have comments for current post
}
})
}
}
})
答案 1 :(得分:1)
I highly recommend first reading my classic answer on a similar question: Firebase data structure and url
Nesting data is in general discouraged in the Firebase Database. There have various reasons for that, but a few:
you can only retrieve a complete node. So if you nest the comments under each post, it means you will automatically get all comments whenever you are getting a post.
you often want different access rules on each of these types (posts vs comments). This is more difficult to manage when you nest them, since permission trickles down.
I would have three top-level lists: posts
and comments
.
posts
$postid
author: "uidOfCoderCody"
title: "Firebase Data Retrieval, Path Inside Path"
body: "I would like to know if it possible to..."
comments
$postid
$commentid
author: "uidOfZassX"
comment: "Here is sample code of how it should work."
Since the comments are stored under the same $postid
of the post itself, you can easily look up the comments for a post.
Depending on the use-cases that your app covers, you'll need to adapt or (more likely) expand this data model to efficiently allow your use-cases. For learning more, I also recommend reading this article on NoSQL data modeling.