GameScore
个对象有一个名为Relation
的{{1}}字段
如何在查询中计算此关系中的所有对象:
Badges
我需要类似的东西:
var GameScore = Parse.Object.extend("GameScore");
var query = new Parse.Query(GameScore);
query.equalTo("playerName", "Dan Stemkoski");
query.find({
success: function(results) {
alert("Successfully retrieved " + results.length + " scores.");
// Do something with the returned Parse.Object values
for (var i = 0; i < results.length; i++) {
var object = results[i];
alert(object.id + ' - ' + object.get('playerName'));
}
},
error: function(error) {
alert("Error: " + error.code + " " + error.message);
}
});
或
object.Badges.count
答案 0 :(得分:2)
// return a promise that's fulfilled with a badges count for the passed GameScore
function badgeCountOfGameScore(gameScore) {
var relation = gameScore.get("Badges"); // it must have a relation col called Badges for this to work
return relation.query.find().then(function(results) {
return results.length;
});
}
现在您的原始函数使用promises重做(并使用下划线来更好地处理数组)...
var _ = require("underscore");
function bunchOfBadgeCounts() {
var GameScore = Parse.Object.extend("GameScore");
var query = new Parse.Query(GameScore);
query.equalTo("playerName", "Dan Stemkoski");
return query.find().then(function(results) {
alert("Successfully retrieved " + results.length + " scores.");
var promises = _.map(results, function(object) {
return badgeCountOfGameScore(object);
});
return Parse.Promise.when(promises);
}).then(function() {
alert("Counts = " + JSON.stringify(_.toArray(arguments)));
}, function (error) {
alert("Error = " + JSON.stringify(error));
});
}
答案 1 :(得分:2)
Parse.Relation
对象实际上是一个查询描述,它将返回该关系中的对象,因此对于这种情况,您需要为每个GameScore
运行另一个查询:
query.find().then(function (gameScores) {
alert("Successfully retrieved " + gameScores.length + " scores.");
var countPromises = gameScores.map(function (gs) {
// the following executes a count() query, which is severely penalized by Parse
return gs.get('Badges').query().count()
.then(function (count) {
// this extra step is to add the retrieved count as an extra property to the GameSccore object,
// instead of returning only the counts
gs.count = count;
return gs;
});
});
return Parse.Promise.when(countPromises);
}).then(function () {
var gameScoresWithBadgeCount = Array.prototype.slice.call(arguments);
}).fail(function(error) {
alert("Error: " + error.code + " " + error.message);
});
这导致了很多额外的往返(我假设你因为alert()
而在浏览器环境中),并且调用另外受Parse限制的count()
个查询。
我建议您将计数缓存保留为GameScore
类的额外字段,并通过CloudCode挂钩进行相应更新。或者,您可以尝试避免使用Relation
并尽可能使等效using an Array field成为可能,通过该include,您可以根据需要始终https://jsfiddle.net/461huu5g/1/相关徽章,或者在不查询相关徽章的情况下进行计数!