这不是一个理想的数据结构。如果汽车确实与用户有 1:1 的关系,如数据所示,那么应该简单地按用户存储它们,然后查询特定的用户 ID:
{
"cars": {
"ted": {
...
}
}
}
现在按用户查询汽车非常简单:
var ref = new Firebase("https://<YOUR-FIREBASE-APP>.firebaseio.com/");
$scope.cars = $firebaseArray(ref.child('cars/<USER ID>'));
如果汽车不能按用户拆分,因为它们具有 n:1 关系,那么 a query 可以提供相同的功能(确保您 index them on the server):
var ref = new Firebase("https://<YOUR-FIREBASE-APP>.firebaseio.com/");
var query = ref.child('cars').orderByChild('name').equalTo('ted');
$scope.cars = $firebaseArray(query);
如果您想建立 n:n 关系,则将用户索引到汽车更合适:
"cars": {
"-JRHTHaIs-jNPLXOQivY": {
"type": "Honda",
"year": "2008",
"color":"red"
},
...
},
"owners": {
"ted": {
"-JRHTHaIs-jNPLXOQivY": true,
...
}
}
现在为给定用户获取汽车有点困难,但仍然不无道理:
angular.factory('CachedCarList', function() {
// a simple cache of Firebase objects looked up by key
// in this case, a list of cars that have an n:n relationship to users
var carsRef = new Firebase("https://<YOUR-FIREBASE-APP>.firebaseio.com/cars");
var carsLoaded = {};
return {
get: function(carId) {
if( !carsLoaded.hasOwnProperty(carId) ) {
carsLoaded[cardId] = $firebaseObject(carsRef.child(carId));
}
return carsLoaded[carId];
},
destroy: function(carId) {
angular.forEach(carsLoaded, function(car) {
car.$destroy();
});
carsLoaded = {};
}
}
});
angular.factory('CarList', function($firebaseArray, CachedCarList) {
var ref = new Firebase("https://<YOUR-FIREBASE-APP>.firebaseio.com/");
var CarsIndexed = $firebaseArray.$extend({
'$$added': function(snapshot) {
// when something is added to the index, synchronize the actual car data
// we use the $loaded promise because returning it here will make AngularFire
// wait for that data to load before triggering added events and Angular's compiler
return CachedCarList.get(snapshot.key()).$loaded();
},
'$$updated': function(snapshot) {
return false; // our cars update themselves, nothing to do here
}
});
return function(userId) {
// when a list of cars is requested for a specific user, we return an CarsIndexed
// than synchronizes on the index, and then loads specific cars by referencing their
// data individually
return new CarsIndexed(ref.child('owners/'+userId));
}
});
firebase-util's NormalizedCollection 可以帮助简化此过程:
angular.factory('CarList', function($firebaseArray) {
var ref = new Firebase("https://<YOUR-FIREBASE-APP>.firebaseio.com/");
return function(userId) {
var nc new Firebase.util.NormalizedCollection(
ref.child('owners/' + userId),
ref.child('cars')
).select('cars.type', 'cars.year', 'cars.color')
return $firebaseArray(nc.ref());
}
});
Firebase Angular guide 涵盖了许多类似的主题,并且还引入了一个绑定库来代表您处理同步远程/本地数据。
此外,Firebase 文档还涵盖了许多主题,例如数据结构、索引多对一或多对多关系等。我强烈建议您从前到后阅读the guide,然后再继续阅读。