2017-01-12 40 views
1

如何在Firebase数据库中进行查询以获取控制台中的某些子项?例如,从下面的快照中,我怎样才能查询得到Image,其中Des: 11如何使Firebase数据库查询获得一些使用Swift 3的孩子?

This is a snapshot for my console in firebase database

我使用这个代码:

func loadData(){ 


    Ref=FIRDatabase.database().reference().child("Posts") 

    Handle = Ref?.queryOrdered(byChild: "11").observe(.childAdded ,with: { (snapshot) in 

     if let post = snapshot.value as? [String : AnyObject] { 

      let img = Posts() 

      img.setValuesForKeys(post) 

      self.myarray.append(img) 

       self.tableView.reloadData() 

     } 

    }) 

} 
+0

'ref?.queryOrdered(byChild:“Des”)。queryEqual(toValue:“11” AnyObject] { // .... } })' –

+0

感谢您的帮助,但是这个错误出现在调试中(使用未指定的索引,请考虑在/ posts到您的安全规则中添加“.indexOn”:“Des”为更好的性能) –

+0

这是不是一个错误..它建议你改变你的规则更好的性能..但仍然你的项目与此警告 –

回答

2

厄尔尼诺Capitain说,你需要使用:也

func loadData(){ 

    let ref = FIRDatabase.database().reference().child("Posts") 

    ref?.queryOrdered(byChild: "Des").queryEqual(toValue: "11").observe(.childAdded, with: { snapshot in 
     if let post = snapshot.value as? [String : AnyObject] { 
      // do stuff with 'post' here. 

     } 
    }) 

} 

,正如他所说,你您需要设置您的安全规则,以允许您通过'Des'或您要查询的任何其他子节点进行搜索。此外,你需要设置规则,允许你读访问查询地点:

{ 
    "rules": { 
    ".read": "auth != null", 
    ".write": "auth != null", 

    "Posts": { 
     "$someID": { 
     ".indexOn": ["Des"] 
     } 
    } 
    } 
} 

但是,你不会得到“只图像”不过,你的查询将返回整个节点。在这种情况下,上面的查询将返回rrrrrr节点。如果let post = snapshot.value as?[String:

+0

我这样做就像你回答,但仍然当我运行我的项目时,它看起来是空的,没有什么东西可以显示。 –

+0

好的。现在它的工作非常感谢你 –

+0

为我工作,谢谢。我一直在使用这里面返回所有的数据:: databaseRef.child(“用户”)queryOrderedByKey()观察(.childAdded,具有:{快照 但想下载,如果满足一定的标准和代码效果很好 – PhilipS

相关问题