Luckyy
Luckyy

Reputation: 1031

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

Upvotes: 10

Views: 28200

Answers (2)

Govind Samrow
Govind Samrow

Reputation: 10189

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();
        });
    });
});

Upvotes: 0

Frank van Puffelen
Frank van Puffelen

Reputation: 600126

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.

Upvotes: 10

Related Questions