这是场景:我有一个主题列表,每个主题都包含帖子,并且每个帖子都被用户列表“喜欢”。因此我的数据看起来像这样:
"topics": {
"topic1": {
"posts": {
"post1": true,
"post2": true
}
}
},
"posts": {
"post1": {
"title": "An awesome post",
"likes": {
"user1": true
}
},
"post2": {
"title": "An even better post",
"likes": {
"user1": true,
"user2": true
}
}
},
"users": {
"user1": {
"name": "Mr. T",
"email": "t@t.com"
},
"user2": {
"name": "Mr. Hello World",
"email": "hello@world.com"
}
}
我(认为我)知道如何使用 Firebase.util ( http://firebase.github.io/firebase-util ) 获取该主题的所有帖子:
Firebase.util.intersection(
fb.child('topics').child('topic1').child('posts'),
fb.child('posts')
)
但是现在我希望每个帖子都包含喜欢该帖子的用户的姓名。如何做到这一点?
可能不会改变任何东西,但这一切都发生在 AngularFire 中。
最佳答案
See a working example here
这种非规范化的要点是在您抓取帖子时获取用户。没有什么比听起来更复杂的了。去抓他们吧。
Firebase 在内部做了大量工作来优化请求,并为所有监听器重新使用相同的套接字连接,因此这是非常高效的——几乎没有比下载的字节量更多的开销,无论它们是否被分成单独的路径或存储在一起。
HTML:
<h3>Normalizing user profiles into posts</h3>
<ul ng-controller="ctrl">
<li ng-repeat="post in posts | orderByPriority" ng-init="user = users.$load(post.user)">
{{user.name}}: {{post.title}}
</li>
</ul>
JavaScript:
var app = angular.module('app', ['firebase']);
var fb = new Firebase(URL);
app.controller('ctrl', function ($scope, $firebase, userCache) {
$scope.posts = $firebase(fb.child('posts'));
$scope.users = userCache(fb.child('users'));
});
app.factory('userCache', function ($firebase) {
return function (ref) {
var cachedUsers = {};
cachedUsers.$load = function (id) {
if( !cachedUsers.hasOwnProperty(id) ) {
cachedUsers[id] = $firebase(ref.child(id));
}
return cachedUsers[id];
};
cachedUsers.$dispose = function () {
angular.forEach(cachedUsers, function (user) {
user.$off();
});
};
return cachedUsers;
}
});
关于firebase - 如何加入在 Firebase 中深入两级以上的非规范化数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23123269/