2016-08-15 75 views
1

我试图在firebase中创建一个1到多个数据结构。我的两个物体看起来像这样1 to many firebase query

category: 
{ 
    cat1: { 
     name: 'Category 1' 
    }, 
    cat2: { 
     name: 'Category 2' 
    } 
} 

products: 
{ 
    product1: { 
    name: 'Product 1', 
    categories: { 
     cat1: true 
    } 
    }, 
    product2: { 
    name: 'Product 2', 
    categories: { 
     cat1: true, 
     cat2: true 
    } 
    } 
} 

现在我究竟会查询该数据获得发言权所有类别产品2? 我已经试过这里面让我回所需要的数据,但它似乎效率低下,不符合文档如何似乎表明你做....

var ref = new Firebase("https://<my-firebase-url>/products/product2"); 
    var catRef = new Firebase("https://<my-firebase-url>/category"); 
    ref.once('value', function(snap) { 
     var result = snap.val(); 
     Object.keys(result.categories).map(key => { 
     catRef.child(key).once('value', function(category){ 
... //add category to array etc 
     } 
     } 
    } 

该文档建议使用child_added事件,但当我想要整个列表不仅仅是当孩子被添加时,这是如何有意义的? (https://www.firebase.com/docs/web/guide/structuring-data.html):

// List the names of all Mary's groups 
var ref = new Firebase("https://docs-examples.firebaseio.com/web/org"); 
// fetch a list of Mary's groups 
ref.child("users/mchen/groups").on('child_added', function(snapshot) { 
    // for each group, fetch the name and print it 
    String groupKey = snapshot.key(); 
    ref.child("groups/" + groupKey + "/name").once('value', function(snapshot) { 
    System.out.println("Mary is a member of this group: " + snapshot.val()); 
    }); 
}); 
+0

上firebase.com该文档已被弃用。使用新的网站:firebase.google.com,关于'child_added',它不仅检索新添加的孩子,还检索现有的孩子。查看Firebase [升级指南](https://firebase.google.com/support/guides/firebase-web)。 –

+1

关于“循环加载”的效率。这是新开发Firebase的开发人员常见的问题。但是,Firebase通过单个连接加载项目并管理请求,因此对于合理大小的数据集通常非常快。请参阅http://stackoverflow.com/questions/35931526/speed-up-fetching-posts-for-my-social-network-app-by-using-query-instead-of-obse/35932786#35932786以获取更长的解释。 –

回答

3

为了得到属于产品2的所有类别,你应该使用:现在

firebase.database().ref('products/product2/categories').on('child_added', snapshot => { 
    firebase.database().ref('category/'+snapshot.key).on('value', snap => { 
     console.log(snap.val().name + ' belongs to product2'); //Will print Category 1 and Category 2 
    }); 
}):