使用 OrderByChild 使用 Firebase 查询数据

Query data with Firebase with OrderByChild

我有如下数据结构

{
  "advisors" : {
    "0ea9bab6-415e-4900-8698-ac03a1ef4518" : {
      "description" : "",
      "price" : 0,
      "title" : ""
    },
    "cc31c353-ca6a-440d-b188-af2016f72aef" : {
      "description" : "",
      "price" : 0,
      "title" : ""
    },
    "d8403e9b-fb74-4425-874f-2d125cd07a68" : {
      "description" : "I know every corner in the arab countries.",
      "price" : "50",
      "title" : "Best guide in the middle east"
    }
  },
  "advisors-countries" : {
    "0ea9bab6-415e-4900-8698-ac03a1ef4518" : {
      "Angola" : "true"
    },
    "cc31c353-ca6a-440d-b188-af2016f72aef" : {
      "Angola" : "true"
    }
  },

我想进行以下查询:给我列表中包含安哥拉的所有顾问的价格。

我尝试了下一个代码,只检索 Advisor-countries 的 child,其中 Angola=true。

var advisors = (ref.orderByChild("Angole").equalTo(true));
$scope.users = $firebaseArray(advisors);
console.log("sync ", $scope.users);

但我一直在顾问 object 中得到 null object。

要使用 AngularFire 轻松进行查询,您需要重新设计数据结构。

"advisors-countries" : {
    "0ea9bab6-415e-4900-8698-ac03a1ef4518" : {
      "Angola" : "true",
      "price": 0
    },
    "cc31c353-ca6a-440d-b188-af2016f72aef" : {
      "Angola" : "true",
      "price": 0
    }
}

您应该在 advisors-countries 位置包含价格和任何其他相关数据。如果您担心重复数据,那没关系。 You can use multi-path updates to keep your data consistent.

那么您的查询将有效:

var query = ref.orderByChild("Angola").equalTo(true);

现在,为什么您看到 $scope.users.

为空

当您将 $scope.users 登录到控制台时,它将是 null,因为一开始没有数据。下载数据是一个异步动作,所以一开始是不可用的。

要调试此操作,请使用 $loaded()

$scope.users = $firebaseArray(advisors);
$scope.users.$loaded().then(function(data) {
  console.log(data);
  console.log(data === $scope.users);
});

在第一个日志中,您将获得任何存在的数据。在第二个日志中,您会看到 data 参数与 $scope.users 对象相同。这意味着您没有使用 $loaded(),因为当可用时,它将在您的模板中使用。