加入Firebase数据库 [英] Joins in the Firebase Database

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

问题描述

firebase数据结构为

The firebase data structure is

{
  "eventAttendees" : {
    "fm" : {
      "1" : "David",
      "2" : "Alice"

    }
  },
  "events" : {
    "fm" : {
      "date" : "2017-06-16",
      "name" : "Firebase Meetup"
    },
    "gm" : {
      "date" : "2017-08-12",
      "name" : "Meet Linh"
    }
  },
  "users" : {
    "1" : {
      "email" : "david@gmail.com",
      "name" : "David"
    },
    "2" : {
      "email" : "alice@gmail.com",
      "name" : "Alice"
    },
    "10" : {
      "email" : "khanh@gmail.com",
      "name" : "Khanh"
    }
  }
}

我想找到所有参加fm活动的用户.这是我的代码:

I want to find all users who go to fm event. Here is my code:

let ref = Database.database().reference()
ref.child("eventAttendees/fm").observe(.value, with: { (snapshot) in
           print (snapshot.key)
            ref.child("users/\(snapshot.key)").observeSingleEvent(of: .value, with: { (userSnapshot) in
                let content = userSnapshot.value as? [String : AnyObject] ?? [:]
                print(content)
            })
        })

我遵循本教程 https://youtu.be/Idu9EJPSxiY?t=3m14s

根据教程 snapshot.key 应该返回"1","2",以便 ref.child("users/\(snapshot.key)")将为 ref.child("users/1")

Base on the tutorial snapshot.key should return "1", "2", so that ref.child("users/\(snapshot.key)") will be ref.child("users/1")

但是在我的代码上, snapshot.key 返回"fm",而 ref.child("users/\(snapshot.key)") ref.child("users/fm")

But on my code, the snapshot.keyreturn "fm", and ref.child("users/\(snapshot.key)") will be ref.child("users/fm")

我的代码哪里出问题了?

Where is the problem in my code?

推荐答案

eventAttendees/fm 下,您有多个孩子.因此,您也需要遍历代码中的那些子节点:

Under eventAttendees/fm you have multiple children. So you will need to loop over those child nodes in your code too:

let ref = Database.database().reference()
ref.child("eventAttendees/fm").observe(.value, with: { (snapshot) in
    for child in snapshot.children.allObjects as [FIRDataSnapshot] {
        print (child.key)
        ref.child("users/\(child.key)").observeSingleEvent(of: .value, with: { (userSnapshot) in
            let content = userSnapshot.value as? [String : AnyObject] ?? [:]
            print(content["name"])
        })
    }
})

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

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