Firebase: How to retrieve data from two tables usi

2019-05-30 15:31发布

问题:

I come from an SQL background and recently started using Firebase for building an ionic shopping cart. This is the database schema:

To retrieve a user's cart, i used the following

    var user_id="user1"; // Temporary initialised

    var refCart = new Firebase("https://testing.firebaseio.com/cart");
    var cart=$firebase(fireBaseData.refCart().child(user_id)).$asArray();

This gives the result:

item1 1
item2 2
item3 5

So tried using foreach()

var refMenu = new Firebase("https://testing.firebaseio.com/menu");
refCart.child(user_id).on("value", function(snapshot) {

    snapshot.forEach(function(childSnapshot) {

      var item_id = childSnapshot.name();
      var qty = childSnapshot.val();

      //var data= refMenu.child(item_id).val();  
      // val is not a function

      //var data= refMenu.child(item_id).exportval(); 
      // exportval is not a function

      //var data = $firebase (refMenu.child(item_id)). $asArray(); 
      // Give me an array of objects , ie attributes - OK! But what to do next ?

      //console.log("DATA",data );

      console.log("Item",item_id+" "+qty);

   });

});

How can i use item_id to retrieve item details.

Is it the correct way of doing data retrieval from multiple tables?

Update:

Using on() function , i managed to get the item attributes.

    refMenu.child(item_id).on("value", function(snapshot) {
      console.log("Price",snapshot.val().price);
    });

But is there any better implementation for the same.

Is there any better ways to retrieve (from the server side) specific attributes for the item. Like in SQL

SELECT name,price, ... from menu;

回答1:

NOTE: .on('event', callback) method will call your callback every time the event is fired.

If you need to retrieve data from a reference once, you should use: .once('event', callback)

NOTE2: snapshot.val() will give you a JSON object that you can assign to a variable

I would do it this way:

refCart.child(user_id).on("value", function(snapshot) {

  snapshot.forEach(function(childSnapshot) {
    var item_id = childSnapshot.name();
    var qty = childSnapshot.val();

        refMenu.child(item_id).once("value", function(snapshot) {
          var item = snapshot.val()
          console.log(item.name +' '+ item.price)
        });

 });

});

Hope it helps ;)