swift firebase一对多的例子?

时间:2016-09-05 04:23:02

标签: swift firebase firebase-realtime-database

我在下面创建了2个表。我想选择表格朋友,我想从表格用户显示名称?任何人都可以帮助我,例如swift,谢谢你。

表用户

 id
 name
 email

表朋友

 id
 user_id
 friend_id

1 个答案:

答案 0 :(得分:0)

您的实时数据库应该是这样的。

{
    "users": {
        "1": {
            "name": "John Doe",
            "email": "john@example.com"
        },
        "2": {
            "name": "Jane Doe",
            "email": "jane@example.com"
        }
    },
    "user-friends": {
        "1": {
            "2": true
        },
        "2": {
            "1": true
        }
    }
}

为了得到约翰的朋友,我们观察路径/user-friends/1

let uid = 1 // the uid of the user we want the friends of
let ref = FIRDatabase.database().reference().child('user-friends/\(uid)')

ref.observeEventType(.ChildAdded, block: { snapshot in

    let uid = snapshot.key // the uid of a user who is John's friend
    let ref = FIRDatabase.database().reference().child('users/\(uid)')

    ref.observeSingleEventOfType(.Value, block: { snapshot in
        if let json = snapshot.value as? [String:AnyObject] {
            print(json["name"])
        }
    })
})