gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 09:54:54 27 4
gpt4 key购买 nike

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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com