2016-08-31 45 views
0

我想知道是否有可能在當前路徑的完成塊內訪問另一條路徑。Firebase數據檢索,路徑內部路徑

我使用它的方式如下...我有一個社交媒體應用程序,「帖子」路徑。很顯然,我可以從這些信息中獲取所有信息。我想爲每個帖子創建「評論」。那就是我希望有一條通往「評論(S)」的道路。有人建議實現這一目標?

回答

1

我強烈建議先閱讀過類似的問題我的回答經典:Firebase data structure and url

嵌套數據一般不鼓勵在火力地堡數據庫。造成這種情況的原因有很多種,但有幾種:

  • 您只能檢索完整的節點。因此,如果您在每篇文章下嵌套評論,這意味着您在獲得文章時會自動獲得所有評論。

  • 您經常希望在這些類型中的每一個上發佈不同的訪問規則(帖子vs評論)。當你嵌套它們時,這是更難以管理的,因爲權限逐漸下降。

我想有三個頂級名單:postscomments

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." 

由於意見在職位本身的相同$postid存儲,您可以輕鬆地查找了文章的評論。

根據您的應用涵蓋的用例,您需要調整或(更可能)擴展此數據模型以有效地允許您的用例。爲了學習更多,我還推薦閱讀NoSQL data modeling上的這篇文章。

+0

我更喜歡你的策略。我猜我可以使用點符號訪問文章的自動識別號? – CoderCody

+0

我不確定你的意思。你一定可以獲得帖子的自動編號/密鑰。在調用'let newPostRef = ref.childByAutoId()'後,您可以通過'newPostRef.key'獲取它。 –

+0

@CoderCody我的答案如下,是如何從Firebase讀取,如果結構如上所述。 – ZassX

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 

        } 
       }) 
      } 
     } 
    }) 
+0

只要我能接受它,我會的。感謝您的幫助! – CoderCody