GameScore对象具有一个名为RelationBadges字段。
如何在查询中获取此关系中所有对象的计数:

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


要么

object.Badges.length

最佳答案

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()我假设您在浏览器环境中),并调用count()查询,这些查询还受Parse限制。

我可以建议您将计数缓存保留为GameScore类的额外字段,并通过CloudCode挂钩相应地对其进行更新。另外,您可以尝试避免使用Relation并尽可能地使用等价的using an Array field,通过该方法,您始终可以根据需要始终include相关徽章,也可以完全不查询它们而获得它们的数量!

09-05 05:26