【问题标题】:Firebase: How to retrieve data from two tables using idFirebase:如何使用 id 从两个表中检索数据
【发布时间】:2016-10-20 19:10:48
【问题描述】:

我来自 SQL 背景,最近开始使用 Firebase 构建离子购物车。这是数据库架构:

为了检索用户的购物车,我使用了以下

    var user_id="user1"; // Temporary initialised

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

这给出了结果:

item1 1
item2 2
item3 5

所以尝试使用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);

   });

});

如何使用 item_id 来检索 item details

从多个表中检索数据是否正确?

更新:

使用on() 函数,我设法获取了项目属性。

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

但是有没有更好的实现方式。

有没有更好的方法来检索(从服务器端)项目的特定属性。 就像在 SQL 中一样

SELECT name,price, ... from menu;

【问题讨论】:

    标签: ionic-framework firebase firebase-realtime-database


    【解决方案1】:

    注意:.on('event', callback) 方法将在每次触发事件时调用您的回调。

    如果您需要从引用中检索一次数据,您应该使用:.once('event', callback)

    注意 2:snapshot.val() 将为您提供一个 JSON 对象,您可以将其分配给一个变量

    我会这样做:

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

    希望对你有帮助;)

    【讨论】:

    • 嘿@Devid,我想从两个表中检索数据,即购物车和菜单。有没有更好的选择。
    • 您不必像在 SQL 中那样在 1 个“查询”中完成所有操作。从购物车中检索数据然后从菜单中检索您需要的数据是一个很好的解决方案。这是进行连接的firebase方式。据我了解,您唯一可以改进的是缓存您的“项目”客户端,这样您就不需要多次查询 Firebase 来获取同一个项目。
    • 谢谢....但我想要一个更好的方法。如您所见,将菜单项保存在购物车中会导致冗余。在这种方法中,我几乎需要两个数组。我想知道 NoSQL 是否适合此类应用程序。
    • 是的,你是对的,这会产生冗余,但没关系。在我看来,您的解决方案很好,并且您构建数据的方式使检索它们变得容易。但我不是大师 :) 我认为这是一个有趣的文件:firebase.com/docs/web/guide/structuring-data.html希望它有所帮助
    • PS:“您通常根据您想要检索它们的方式来构建数据。”这有助于具有 SQL 背景的人了解如何构造数据。也许你会发现它有帮助;)
    猜你喜欢
    • 1970-01-01
    • 2017-06-10
    • 1970-01-01
    • 2021-11-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多