【问题标题】:Simple Querying Firebase Database简单查询 Firebase 数据库
【发布时间】:2017-08-16 11:25:01
【问题描述】:

我在 Firebase 上创建了一个具有以下结构的数据库:

employees
    employee-id
        name: "Jhon Doe"
        bio: "Software Developer"
        birthday: "03/23/1986"
recognitions
    recognition-id
        date: "03/23/2017"
        employee: employee-id
        type: "Team Working"

如何从我的数据库中获得所有的认可以及员工的数据在同一个对象中?

我正在使用 AngularJS 在网络上开发它。

【问题讨论】:

  • 澄清一下,您想用所有recognitionsrecognition-id 对象列表)和员工的employee-id 对象数据构建 1 个对象?
  • @RadicalFanatic 正确!使用 ID 链接两个信息的一个对象
  • 太棒了!我建议为每个 employer-id 对象添加 recognition-id 引用。如果允许您进行此更改,我可以帮助您:)
  • @RadicalFanatic 事实上,每个员工都可以得到很多认可。你是怎么做到的?

标签: javascript angularjs firebase firebase-realtime-database nosql


【解决方案1】:

您可以只创建自己的对象,因为Firebase 不具备在数据库端连接的能力。

var bigObject = {};
// Find all recognitions
var ref = firebase.database().ref("recognitions");
ref.once("value").then(function(snapshot) {
    bigObject = snapshot.val();

    // Loop through all recognitions
    for(o in bigObject) {
        var ref2 = firebase.database().ref("employees").child(bigObject[o].employee);
        ref.once("value").then(function(snapshot2) {
            bigObject[o].employee = snapshat2.val();
        }
    }
});

你会得到这样的东西:

recognitions
    recognition-id
        date: "03/23/2017"
        employee
            name: "Jhon Doe"
            bio: "Software Developer"
            birthday: "03/23/1986"
        type: "Team Working"

如果您使用的是 JavaScript SDK(您没有标记 AngularFire),这将起作用

【讨论】:

  • 非常感谢!你的帮助对我非常有用。但请检查您的答案是否有一些错误。我把正确的解决方案放在下面,以从 Firebase 获取所有信息。
【解决方案2】:

我发现使用唯一 ID 连接不同引用的正确方法是以下代码:

var bigObject = {};

// Find all recognitions
var ref = firebase.database().ref('recognitions');
ref.once('value').then(function(snapshot) {
    bigObject = snapshot.val();
    // Loop through all recognitions
    for (o in bigObject) {
        var ref2 = firebase.database().ref('employees').child(bigObject[o].employee);
        ref2.once('value').then(function(snapshot2) {
            bigObject[o].profile = snapshot2.val();
            // Bind the content to the view
            $scope.$apply(function() {
                $scope.data = bigObject;
            });
        });
    }
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-11-02
    • 2021-10-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-07
    相关资源
    最近更新 更多