【问题标题】:Firebase angular many to many relation queryFirebase角度多对多关系查询
【发布时间】:2016-07-18 16:02:01
【问题描述】:

我有一个相当简单的组和人员的 json 结构,我正在努力从 firebase 获取/读取每个人的组名列表。这是我尝试过的。我花了几天调试不成功。非常感谢您的帮助。

JSON:

{
"groups" : {
"one" : {
  "members" : {
    "-KLxjv9OnQB2l5Ohr-7I" : true
  },
  "name" : "group alpha"
},
"two" : {
  "members" : {
    "-KM4oXjftRZZ5DXYt4B2" : true
  },
  "name" : "group beta"
},
"three" : {
  "members" : {
    "-KM4oXjftRZZ5DXYt4B2" : true
  },
  "name" : "group gamma"
}
},
"persons" : {
"-KLxjv9OnQB2l5Ohr-7I" : {
  "groups" : {
    "one" : true
  },
  "personName" : "name1",
  "personTitle" : "title1"
},
"-KM4oXjftRZZ5DXYt4B2" : {
  "groups" : {
    "two" : true
  },
  "personName" : "name2",
  "personTitle" : "title2"
  }
 }
}

APP.JS:

$scope.personsGroup = function(personObj){
var baseRef = new Firebase("https://un-cms-13264.firebaseio.com/");
var personsRef = baseRef.child('persons');
var groupsRef = baseRef.child('groups');
var res=[];
    for(var i=0;i<Object.keys(personObj.groups).length;i++){
    var groupKey=Object.keys(personObj.groups)[i]
    res.push($firebaseArray(groupsRef.child(groupKey)));
    };
    return res;

}

HTML:

<div class="row" ng-repeat="person in persons">

<div class="col-lg-3"></div>
<div class="col-lg-3">{{person.personName}}</div>
<div class="col-lg-3"></div>
<div class="col-lg-3 groupsList">
<ul><li ng-repeat="group in personsGroup(person)">{{group.name}}</li></ul>
</div>

</div>

【问题讨论】:

  • 所以你想返回一个人所在的组的名称?
  • 您遇到了什么问题?另外:如果您可以在 jsfiddle/jsbin 中重现问题,人们可以使用它并查看事情是如何工作的(以及可能为什么不这样)。您会发现这样可以获得更多帮助。
  • 是的@theblindprophet 这正是我的问题。我得到空白条目,但没有得到组的名称。

标签: angularjs firebase many-to-many firebase-realtime-database


【解决方案1】:

最好的方法是将$firebaseArray 附加到$scope 变量:

var ref = new Firebase("https://un-cms-13264.firebaseio.com/").child("persons").child(some-person).child("groups");
$scope.personsGroup = $firebaseArray(ref);

// When loaded
$scope.personsGroup.$loaded(function(data) {
     // can do something
}, function(error) {
     // error
});

如何确定some-person 取决于您。您可以查询 persons 树并存储所有人员或将其存储在数组或对象中。

<ul>
    <li ng-repeat="(key, value) in personsGroup">{{ key }}</li>
</ul>

我不建议personGroup(person),因为$firebaseArray 是一个异步调用,我觉得它可能真的很紧张。聪明一点,如果你愿意,你也可以一次调用整个persons树:

var ref = new Firebase("https://un-cms-13264.firebaseio.com/").child("persons");
$scope.persons = $firebaseArray(ref);

然后做一些迭代。

【讨论】:

  • 所以现在我从个人实体中获取组键(“一”、“二”等),但我如何将它与来自组实体的 group.name(“组 alpha” “组测试版”等)?
  • 引用它:ref = new Firebase("https://un-cms-13264.firebaseio.com/").child("groups").child(the-group); 然后使用可以访问name
  • 或者你可以只存储以persons开头的组名,而不是onetwo
猜你喜欢
  • 2017-03-16
  • 2016-07-24
  • 2021-10-03
  • 2018-11-02
  • 2015-10-26
  • 2011-08-08
  • 2015-05-29
  • 2019-10-28
  • 2019-01-31
相关资源
最近更新 更多