Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to do joins on Firebase tables

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

like image 571
Luckyy Avatar asked Sep 07 '14 15:09

Luckyy


People also ask

What does getKey () do Firebase?

Calling the getKey() method on this reference will return the auto-generated key which may then be used to store a corresponding value. Using Firebase to generate unique keys in this way is also of particular use when an app has multiple users creating child nodes at the same path in the tree.

Can we use SQL queries in Firebase?

FireSQL is a library built on top of the official Firebase SDK that allows you to query Cloud Firestore using SQL syntax. It's smart enough to issue the minimum amount of queries necessary to the Firestore servers in order to get the data that you request.

What is a joining table?

A joined table specifies an intermediate result table that is the result of either an inner join or an outer join. The table is derived by applying one of the join operators: CROSS, INNER, LEFT OUTER, RIGHT OUTER, or FULL OUTER to its operands.


1 Answers

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.

like image 108
Frank van Puffelen Avatar answered Oct 02 '22 14:10

Frank van Puffelen