Firebase - 组织排名系统。随着喜欢的历史

Firebase - organising ranking system. Along with history of likes

我正在构建一个应用程序,用户可以在其中 post、删除和排名(喜欢、不喜欢)彼此的 post。 在个人资料页面上,用户还可以查看他曾经喜欢的post。

目前我正在考虑制作类似的结构(true - 表示喜欢,false 表示不喜欢,空表示没有评级):

{
"ranks": {
    "post1": {
      "user1": "true",
      "user2": "false",
      "user3": "false"
    },
    "post2": {
      "user1": "true",
      "user3": "true"
    },
    "post3": {
      "user1": "false",
      "user2": "true",
      "user3": "true"
    }
  }
}

一切看起来都很好,直到我需要检索用户曾经喜欢的所有 post。 例如。对于 user1 将是 [post1,post2]。对于用户 2 - [post3].

然后我想按以下方式重组它:

{
"ranks_by_user": {
    "user1": {
      "post1": "true",
      "post2": "true",
      "post3": "false"
    },
    "user2": {
      "post1": "false",
      "post3": "true"
    },
    "user3": {
      "post1": "false",
      "post2": "true",
      "post3": "true"
    }
  }
}

然而,这样就更不方便了:如果我删除了一个post,我怎么也删除所有相关的行列呢?无法找出一个查询来查找 ranks_by_user 列表中有 post-n 个子项的所有用户。 如何解决这样的结构问题?

所以你的结构是正确的。使用 firebase 的普遍共识是您将拥有重复数据。至于你关于如何删除的第二个问题,因为一切都被扁平化并且没有外键,你将不得不自己连接查询。根据您的模型,这样的事情可能会起作用:

...child('ranks_by_user').orderBy('post2').equalTo(true).once('value', function(){
    //delete record
});
...child('ranks_by_user').orderBy('post2').equalTo(false).once('value', function(){
    //delete record
});

问题是它会很慢,因为 post2 不会被索引。相反,使用您的第一个模型,您将能够查询该记录以查看 liked/disliked 它是谁,然后去删除其他模型记录中的条目。这是我的建议。这里有一些代码(在 angular1 中完成)可以为你做到这一点:

var postId = 'post1';
...child('ranks').child(postId).once('value', function(snapshot){
    angular.forEach(snapshot.val(), function(value, userId){
        ...child('ranks').child(postId).child(userId).remove();
        ...child('ranks_by_user').child(userId).child(postId).remove();
    });
});