如何加入Firebase中两个+级别的非规范化数据

问题描述 投票:4回答:1

这是一个场景:我有一个主题列表,每个主题都包含帖子,每个帖子都被用户列表“喜欢”。因此我的数据看起来像这样:

"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": "[email protected]"
     },
     "user2": {
         "name": "Mr. Hello World",
         "email": "[email protected]"
     }
 }

我(我想)知道如何使用Firebase.util(http://firebase.github.io/firebase-util)获取该主题的所有帖子:

Firebase.util.intersection(
    fb.child('topics').child('topic1').child('posts'),
    fb.child('posts')
)

但现在我希望每篇文章都包含喜欢这篇文章的用户的名字。怎么做到这一点?

可能不会改变任何东西,但这一切都发生在AngularFire中。

firebase firebase-realtime-database angularfire nosql
1个回答
3
投票

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;
    }
});
© www.soinside.com 2019 - 2024. All rights reserved.