热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

如何在Firebase表上进行连接-howtodojoinsonFirebasetables

Iamtryingtogetdatafromtwotableslike(fetchallusersandtheirdetails)我试图从两个表中获取数据(获取所有用户

I am trying to get data from two tables like (fetch all users and their details)

我试图从两个表中获取数据(获取所有用户及其详细信息)

tableOne.on('users', function (snapshot) {
    userId = snapshot.val().userId; // line 1 (results like 1,2,3,4,5,6)
    anotherTable.child('userdetails').child(userId).once('value', function(mediaSnap) {
     // result // line 2
 });
});

but the problem is line 1 executes first for the 6 times and then line 2 that n times resulting in everytime looking for 'where user id is - 6'...isn't joins supported in Firebase?

但问题是第1行首先执行6次,然后第2行执行n次,导致每次都在寻找“用户ID为 - 6”的地方...... Firebase中是否支持加入?

Any help is apreciated

任何帮助都是相关的

2 个解决方案

#1


7  

Your code snippet has a nasty side-effect:

你的代码片段有一个讨厌的副作用:

var userId;
tableOne.on('value', function (snapshot) {
    userId = snapshot.val().userId; // line 1 (results like 1,2,3,4,5,6)
    anotherTable.child('userdetails').child(userId).once('value', function(mediaSnap) {
        console.log(userId + ":" + mediaSnap.val().name);
    });
});

You're not declaring userId as a variable, which means that it becomes a global variable in Javascript. And since the callback function executes asynchronously, there is a good chance that the global values will have changed by the time you need it.

您没有将userId声明为变量,这意味着它将成为Javascript中的全局变量。由于回调函数是异步执行的,因此很有可能在需要时全局值会发生变化。

The solution is simply to make userId a local variable of the callback function:

解决方案只是使userId成为回调函数的局部变量:

tableOne.on('value', function (snapshot) {
    var userId = snapshot.val().userId; // line 1 (results like 1,2,3,4,5,6)
    anotherTable.child('userdetails').child(userId).once('value', function(mediaSnap) {
        console.log(userId + ":" + mediaSnap.val().name);
    });
});

This will ensure that each value of userId is captured inside the function.

这将确保在函数内捕获userId的每个值。

#2


0  

Solution for list join:

列表连接的解决方案:

tableOne.orderByKey().on("value", function (snapshot) {
    //console.log(snapshot.val());
    snapshot.forEach(function (data) {
        tableTwo.once('value').then(function (info) {
            info = info.val();
        });
    });
});

推荐阅读
author-avatar
chucai
这个家伙很懒,什么也没留下,只留下了这个默认个签!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有