如何在Firebase表格上进行连接 [英] how to do joins on Firebase tables
问题描述
$ b
tableOne.on(' (快照){
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
});
});
但是问题是第一行第一次执行了6次然后第二行n次导致每次查找用户标识为-6的地方......不是Firebase支持的连接?
任何帮助都是可以预料的 <您的代码片段有一个令人讨厌的副作用:
解决方案 var userId;
tableOne.on('value',function(snapshot){
userId = snapshot.val()。userId; // line 1(results like 1,2,3,4,5,6)
另一个table.child('userdetails')。child(userId).once('value',function(mediaSnap){
console.log(userId +:+ mediaSnap.val() );
});
});
您没有将 userId
声明为变量,这意味着它成为JavaScript中的全局变量。而且由于回调函数是异步执行的,很可能全局值在你需要的时候会改变。
解决方法是简单地使 userId
回调函数的局部变量:
tableOne.on('value ',function(snapshot){
var userId = snapshot.val()。userId; // line 1(results like 1,2,3,4,5,6)
anotherTable.child(' (userIta)')。child(userId).once('value',function(mediaSnap){
console.log(userId +:+ mediaSnap.val()。name);
});
});
这将确保 userId
被捕获的功能。
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?
Any help is apreciated
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.
The solution is simply to make userId
a local variable of the callback function:
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.
这篇关于如何在Firebase表格上进行连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!