Reputation: 1210
I have created a database on Firebase with the following structure:
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"
How to get all the recognitions from my DB with the data of the employee too in the same object?
I'm developing this on the web using AngularJS.
Upvotes: 2
Views: 133
Reputation: 1210
I found that the correct way to join between differents references using a unique ID, was the following code:
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;
});
});
}
});
Upvotes: 1
Reputation: 7927
You can just create your own object because Firebase
does not have the capability of joins on the database side.
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();
}
}
});
And you'll get something like this:
recognitions
recognition-id
date: "03/23/2017"
employee
name: "Jhon Doe"
bio: "Software Developer"
birthday: "03/23/1986"
type: "Team Working"
This will work if you are using the JavaScript SDK (you didn't tag AngularFire)
Upvotes: 1