从多个孩子检索Firebase数据库 [英] Retrieving From Firebase Database with multiple childs

查看:151
本文介绍了从多个孩子检索Firebase数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在使用Firebase一段时间没有问题,但最近我有一个多个孩子的数据库结构,我有我的代码阅读它的问题。
这里是我的Firebase数据库结构:


$ news $ {
50OzNLsK:{
category:Anuncio,
content:[null,{
paragraph:{
text:Lorem ipsum dolor sit呃elit lamet,consectetaur cillium adipisicing pecu,sed do eiusmod tempor incididunt ut labore et dolore magna aliqua。
$ b $ {
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 b $ btitle:Mi NUeva noticia,
videoURL:https://youtu.be/S0YjUc7K3cw
}
},
users:{
tfeMODxXUnVvhvzntm77pKKtyfz2:{
email:magonicolas@gmail.com,
store:Rinno
$,
tpjn4feUuiTJmsd9lslHTREG1iE2:{
email:nicolas.palacios@rinno.la,
store:Rinno
}
}
}

我的问题是读取内部信息,例如500zNLsK /合作ntent / 1 / parahraph / text或500zNLsK / content / 2 / quote / quoteText中的引用文本

我已经到了这里:

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

self.news = []


如果让snapshot = snapshot.children.allObjects as? [FIRDataSnapshot] {
快照中的快照
{
如果让newsDict = snap.value为? Dictionary< String,AnyObject>
{
print(Mago Dict:\(newsDict))

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



$ b code>

我不能在里面显示内容,它会给出null。
帮助我会非常感激:D

解决方案

您需要对结构进行一些更改让它流畅地工作。这里有一个示例结构让你朝着正确的方向前进:

 news
topic_1
category:topic 1 category
content
content_1
paragraph
text:topic 1 content 1 text
content_2
段落
text:topic 1 content 2 text
date:some date,
likes:12

topic_2
category:topic 2 category,
content
content_1
paragraph
text: 主题2有效1文本
content_2
段落
text:topic 2 content 2 text
date:another date,
likes:425

这里是大多数数据

  newsRef.observe(.value,其中:{snapshot in 

if(sn apshot!.value是NSNull){
print(not found)
} else {

(snapshot?.children) {

//快照是包含新闻的每个节点:topic_1,topic_2
let snap = child as! FDataSnapshot

//将每个节点数据作为字典
让dict = snap.value as! [String:AnyObject]

//我们现在可以访问Dictionary中的每个键:值对
let cat = dict [category]
print(category = \\ \\(cat!))

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

/ / content节点是一个关键字:值为'content'为关键字,
//值为其他关键字:value对的字典
let contentDict = dict [content] as! [String:AnyObject]

//注意到content_1键值对有一个content_1
//和另一个字典
的值key let itemNum1Dict = contentDict [ content_1]为! [String:AnyObject]

// new我们需要获取content_1的值,它是
//'paragraph'和另一个键:值对
let paragraphDict = itemNum1Dict [段落]为! [String:AnyObject]

//几乎就在那里.. paragraphDict有一个
//键值对:text''topic 1 content 1 text'
let theText = paragraphDict [文字]为!字符串
print(text = \(theText))

}
}
})
pre>

一些注意事项:
$ b <1>请不要在Firebase中使用数组。他们是邪恶的,会给你带来极大的悲痛。你的节点名称应该是描述节点的东西(比如'news')和用childByAutoId创建的子值。即使在内容节点中,我也使用了content_1和content_2,但是也应该使用childByAutoId来创建这些节点。2)如果你像我的例子那样迭代节点,节点内应保持一致。你实际上可以绕过这一点,但对于查询等,你总是更好的一致。


<3> 非规范化是正常的。这种结构的作品,但你会得到一些优势,使整个结构更浅。

I have been working with Firebase for a while with no problem, but Recently I have a database structure with multiple childs, And Im having issues reading it on my code. Here is my Firebase Database Structure:

{
  "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" : "magonicolas@gmail.com",
      "store" : "Rinno"
    },
    "tpjn4feUuiTJmsd9lslHTREG1iE2" : {
      "email" : "nicolas.palacios@rinno.la",
      "store" : "Rinno"
    }
  }
}

My problem is reading the internal information, for example the text in 500zNLsK/content/1/parahraph/text or the quote text in 500zNLsK/content/2/quote/quoteText

I have come this far:

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)

                    }
                }
            }

And I can't make appear the inside content, it gives null. Help would me much appreciated :D

解决方案

There are a number of changes you will need to make to your structure to have it work fluidly. Here's an example structure to get you going the right direction:

  "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

Here's the commented code to get to the 'inside' most data

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

        }
    }
})

Some notes:

1) PLEASE don't user arrays in Firebase. They are evil and will cause you great grief. Your node names should be something describing the node (like 'news') and the child values created with childByAutoId. Even within the 'content' node I used content_1 and content_2 but those should also be created with childByAutoId

2) If you are iterating over nodes as in my example, the structure within the nodes should remain consistent. You can actually get around this a bit but for queries etc you are always better off being consistent.

3) Denormalizing is Normal. This structure works but you would gain some advantages making the entire structure shallower.

这篇关于从多个孩子检索Firebase数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆