javascript - 如何在解析中获取关系字段的计数

标签 javascript parse-platform

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

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 Hook 对其进行相应更新。或者,您可以尝试避免 Relation 并创建等效的 using an Array field如果可能的话,你总能通过它include相关徽章(如果需要)或在根本不查询的情况下获取它们的数量!

关于javascript - 如何在解析中获取关系字段的计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34518805/

相关文章:

javascript - 解析云代码-在 "normal"函数中查询用户问题

php - 如何使用 PHP SDK 从 Parse.com 发送推送通知?

Javascript继承调用和应用

javascript - 使 Canvas 内的图像 Sprite 跟随鼠标

javascript - 微调器不工作

ios - 解析 : How to call a cloud method from an email?

ios - 在 Swift 2 中使用 Parse 获取 Twitter 个人资料图片

javascript - 启用复制并粘贴到 HTML 字段

JavaScript:textarea 滚动了多少?

swift - 将 Parse SDK 与 swift 一起使用,PFUser.currentUser().fetch() 不起作用