2016-12-06 2 views
0

저는 Firebase로 아무런 문제없이 작업 해 왔지만 최근에 여러 자식이있는 데이터베이스 구조가 있습니다. 그리고 코드에 문제가 있습니다. 여기 내 중포 기지의 데이터베이스 구조입니다 :여러 자식이있는 Firebase 데이터베이스에서 검색

{ 
    "news" : { 
    "50OzNLsK" : { 
     "category" : "Anuncio", 
     "content" : [ null, { 
     "paragraph" : { 
      "text" : "Lorem ipsum dolor sit er elit lamet, consectetaur cillium adipisicing pecu, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua." 
     } 
     }, { 
     "quote" : { 
      "image" : "http://www.magonicolas.cl", 
      "quoteText" : "textoDelQuote" 
     } 
     } ], 
     "date" : "Hoy", 
     "imgURL" : "https://firebasestorage.googleapis.com/v0/b/rinnofeed.appspot.com/o/images%2Ftanta.jpg?alt=media&token=60f18a95-9919-4d81-ab1c-9976b71590fc", 
     "likes" : 12, 
     "summary" : "Este es el resumen de la noticia", 
     "title" : "Mi NUeva noticia", 
     "videoURL" : "https://youtu.be/S0YjUc7K3cw" 
    } 
    }, 
    "users" : { 
    "tfeMODxXUnVvhvzntm77pKKtyfz2" : { 
     "email" : "[email protected]", 
     "store" : "Rinno" 
    }, 
    "tpjn4feUuiTJmsd9lslHTREG1iE2" : { 
     "email" : "[email protected]", 
     "store" : "Rinno" 
    } 
    } 
} 

내 문제가 예를 들어, 500zNLsK/내용/1/parahraph/텍스트의 텍스트 또는 500zNLsK/내용/2/인용에 인용 텍스트를 내부 정보를 읽기/quoteText

내가 여기까지 온 :

DataService.ds.REF_NEWS.queryOrdered(byChild: "date").observe(.value, with: {(snapshot) in 

      self.news = [] 


      if let snapshot = snapshot.children.allObjects as? [FIRDataSnapshot] { 
       for snap in snapshot 
       { 
        if let newsDict = snap.value as? Dictionary<String, AnyObject> 
        { 
         print("Mago Dict: \(newsDict)") 

         let key = snap.key 
         let new = News() 
         new.configureNews(newsKey: key, newsData: newsDict) 
         self.news.append(new) 

        } 
       } 
      } 

내가 내부 내용을 표시 할 수 없습니다, null를 제공합니다. 도와 주시면 감사하겠습니다. D

+1

[문제를 재현하는 최소 코드] (http://stackoverflow.com/help/mcve)를 공유하십시오. –

+0

나는 지금 편집 한 @FrankvanPuffelen을 가지고 있지만, 누군가가 방금 firebase에서 데이터베이스를 읽는 더 좋은 방법을 원한다면 내가하지 않기로하지 않았습니다. –

+0

Firebase 구조체를 텍스트로 바꿀 수 있습니까? 그것은 우리가 그것을 테스트하거나 스 니펫을 포함 할 수있는 답변을 게시하는 경우 구조를 다시 입력 할 필요가 없도록 도와줍니다. – Jay

답변

2

구조가 유동적으로 작동하려면 구조를 변경해야합니다.

1) 돈 사항 :

여기
"news" 
    "topic_1" 
     "category" : "topic 1 category" 
     "content" 
     "content_1" 
      "paragraph" 
      "text" : "topic 1 content 1 text" 
     "content_2" 
      "paragraph" 
      "text" : "topic 1 content 2 text" 
     "date" : "some date", 
     "likes" : 12 

    "topic_2" 
     "category" : "topic 2 category", 
     "content" 
     "content_1" 
      "paragraph" 
      "text" : "topic 2 cotent 1 text" 
     "content_2" 
      "paragraph" 
      "text" : "topic 2 content 2 text" 
     "date" : "another date", 
     "likes" : 425 

는 '내부'대부분의 데이터

newsRef.observe(.value, with: { snapshot in 

    if (snapshot!.value is NSNull) { 
     print("not found") 
    } else { 

     for child in (snapshot?.children)! { 

      //snapshots are each node withing news: topic_1, topic_2 
      let snap = child as! FDataSnapshot 

      //get each nodes data as a Dictionary 
      let dict = snap.value as! [String: AnyObject] 

      //we can now access each key:value pair within the Dictionary 
      let cat = dict["category"] 
      print("category = \(cat!)") 

      let likes = dict["likes"] 
      print(" likes = \(likes!)") 

      //the content node is a key: value pair with 'content' being the key and 
      // the value being a dictionary of other key: value pairs 
      let contentDict = dict["content"] as! [String: AnyObject] 

      //notice that the content_1 key: value pair has a key of content_1 
      // and a value of yet another Dictionary 
      let itemNum1Dict = contentDict["content_1"] as! [String: AnyObject] 

      //new we need to get the value of content_1, which is 
      // 'paragraph' and another key: value pair 
      let paragraphDict = itemNum1Dict["paragraph"] as! [String: AnyObject] 

      //almost there.. paragraphDict has a key: value pair of 
      // text: 'topic 1 content 1 text' 
      let theText = paragraphDict["text"] as! String 
      print(" text = \(theText)") 

     } 
    } 
}) 

일부 노트에 도착하는 주석 코드의 예를 들면 다음과 같습니다 구조는 당신이 올바른 방향으로 가야입니다 Firebase의 사용자 배열. 그들은 악하며 큰 슬픔을 일으킬 것입니다. 노드 이름은 노드 (예 : '뉴스')를 설명하는 것이고 childByAutoId로 생성 된 자식 값이어야합니다. 'content'노드 내에서도 content_1과 content_2를 사용했지만 childByAutoId를 사용하여 만들어야합니다.

2) 예제에서와 같이 노드를 반복하는 경우 노드 내의 구조는 일관성을 유지해야합니다. 당신은 실제로이 정도를 돌아볼 수 있지만 쿼리 등에서는 항상 일관성을 유지하는 것이 좋습니다.

3) Denormalizing is Normal. 이 구조는 작동하지만 전체 구조를 더 얕게 만드는 몇 가지 이점을 얻을 수 있습니다.

+1

당신에게 자세한 도움을 주셔서 감사합니다!하지만 n 개의 콘텐츠가있는 경우 어떻게 그걸 반복 할 것입니까 –

+1

@MagoNicolasPalacios 'n'콘텐츠는 무엇입니까? 내 대답의 코드는 데이터가없는 경우 나 1 ~ x 개의 자식이있는 경우를 처리합니다. – Jay

+1

@ 제이 내 질문에 [제 스냅 사진에서 데이터를 읽는 데 어려움을 겪고 있습니다.] (http://stackoverflow.com/questions/41212468). 많은 감사 – bibscy

관련 문제