加入不同的节点,使用firebase

时间:2016-12-07 10:48:43

标签: swift firebase firebase-realtime-database

我正在尝试使用firebase做一个示例应用程序,我不太清楚我应该如何检索嵌套的数据。

我们假设我有一个这样的数据库

 {
        "users": {
            "user-1": {
                "email": "email1",
                "matches": [
                    "match-1",
                    "match-2"
                ]
            },
            "user-2": {
                "email": "email2",
                "matches": [
                    "match-1",
                    "match-2"
                ]
            },
            "user-3": {
                "email": "email3",
                "matches": [
                    "match-2"
                ]
            }
        },
        "matches": {
            "match-1": {
                "name": "Match 1",
                "users": [
                    "user-1",
                    "user-2"
                ]
            },
            "match-2": {
                "name": "Match 2",
                "users": [
                    "user-1",
                    "user-2",
                    "user-3"
                ]
            }
        }
    }

我希望获得user-1的所有匹配。 我现在正在做的是观察users.user-1.matches以获取匹配列表,然后观察每个匹配,以便最终的流程为:

  • 观察users.user-1.matches
  • 观察matches.match-1
  • 观察匹配.match-2
  • ...

问题是:如何优化此流程? (比如制作像sql join这样的东西)

我的想法是得到这样的东西

{
    "users": {
        "user-1": {
            "email": "email1",
            "matches": {
                "match-1": {
                    "name": "Match 1",
                    "users": [
                        "user-1",
                        "user-2"
                    ]
                },
                "match-2": {
                    "name": "Match 2",
                    "users": [
                        "user-1",
                        "user-2",
                        "user-3"
                    ]
                }
            }
        }
    }
}

所以我可以立刻观察整个结构。

我在iOS上使用firebase并使用swift,但您可以随意使用您喜欢的每种语言进行回复。

感谢。

1 个答案:

答案 0 :(得分:2)

评论中的答案是一个答案,但让我们简化一下。让我们创建一个用户节点来存储用户,并创建一个匹配节点来跟踪他们所玩的匹配。

然后我们将进行查询以检索用户1在哪个位置匹配:

users
  user-1
    name: "some name"
    email: "somename@thing.com"
  user-2
    name: "another name"
    email: "anothername@thing.com"
  user-3
    name: "cool name"
    email: "coolname@thing.com"

然后匹配节点

matches
  match-1
    name: "Match 1"
    users
        user-1: true
        user-2: true
  match-2
    name: "Match 2"
    users
        user-1: true
        user-2: true
        user-3: true
  match-3
    name: "Match 3"
    users
        user-2: true
        user-3: true

如您所见,我们已将数据结构化以直接解决我们的查询

matchesRef.queryOrdered(byChild: "users/user-1").queryEqual(toValue: true)
                         .observe(.value, with: { snapshot in
     print(snapshot)          
});

,快照将包含节点match-1和match-2但不匹配-3