1

我只是在体验 parse sdk,我想在客户端添加的两个表之间的关系(例如用户喜欢一个帖子)时使用云代码来增加一个 Number 列,在解析文档中,只有用于增加列的代码基于使用afterSave保存对象而不是表之间的关系:

Parse.Cloud.afterSave("Comment", function(request) {
query = new Parse.Query("Post");
query.get(request.object.get("post").id, {
success: function(post) {
  post.increment("comments");
  post.save();
},
error: function(error) {
  console.error("Got an error " + error.code + " : " + error.message);
}
});
});

如何使用 afterSave 更改两个表之间的关系?任何帮助,将不胜感激。

4

2 回答 2

1

我建议改用 beforeSave 。这是我从我的一个项目中提取的示例代码。

Parse.Cloud.beforeSave(ClassConstants.Item.TYPE, function(request, response) {

    if(!request.object.isNew()) {
        // Retrieve the relationship information in json string format. 
        // RELATION_QUEUE here is simply a string "queue"
        var relQueueJsonStr = JSON.stringify(request.object.op(ClassConstants.Item.RELATION_QUEUE));

        if( relQueue !== undefined ) {
            var relQueue = JSON.parse(relQueueJsonStr);
            // Retrieve the operation being performed to this existing object.
            // The value will be "AddRelation" if a the relation "queue" is  
            // being added to this object
            var operation = relQueue.__op;
            if (operation == "AddRelation"){
                console.log("Relation queue is being added");
               // Do what you like here. In your case increment something

                response.success();
            } else {
            // Relation is being removed
                console.log("Relation queue is being removed");
                response.success();
            }
        } else {
            console.log("No queue relation.");
            response.success();
        }
    } else {
        response.success();
    }
});
于 2015-08-30T11:22:27.367 回答
1

经过一些努力解析文档!最后我以这种方式解决了我的问题,它可以很好地计算两个表之间特定对象的关系,希望这可以节省其他人一些时间:

Parse.Cloud.afterSave("SavedObject", function(request) {
  var likeQuery = request.object.relation("likers").query();
  likeQuery.count()(function(likersCount){

      request.object.set("likersCountColumn",likersCount);
      console.log("Likers Count Is : "+ likersCount);
      request.object.save();
  }); 
});
于 2015-08-30T17:32:47.130 回答