好的,过了一会儿,我能够为我的场景找到解决方案。当用户接受另一个用户时,这应该适用于简单的关系。
首先是我的快速代码。需要注意的是,我创建了一个以 PFUser 作为参数的函数。我这样做是为了重构一个更大的函数。这个用户就是我们要在云代码中保存当前用户的用户。
func createRelation(otherUser: PFUser)
{
let fromUser: PFUser = otherUser
let params = NSMutableDictionary()
params.setObject(fromUser.objectId!, forKey: "Friends")
PFCloud.callFunctionInBackground("addFriendToFriendsRelation", withParameters: params as [NSObject : AnyObject] ) {
(object:AnyObject?, error: NSError?) -> Void in
//add the person who sent the request as a friend of the current user
let friendsRelation: PFRelation = self.currentUser!.relationForKey("Friends")
friendsRelation.addObject(fromUser)
self.currentUser!.saveInBackgroundWithBlock({
(succeeded: Bool, error: NSError?) -> Void in
if succeeded {
println("Relation added to the current user")
} else {
println("Handle error in adding relation to current user ")
}
})
}
}
现在解析云代码
Parse.Cloud.define("addFriendToFriendsRelation", function(request, response) {
Parse.Cloud.useMasterKey();
//get the friend requestId from params
var friendRequestId = request.params.Friends;
var query = new Parse.Query(Parse.User);
//get the friend request object
query.get(friendRequestId, {
success: function(friendRequest) {
//get the user the request was from
var fromUser = friendRequest;
//get the user the request is to
var toUser = Parse.User.current() ;
var relation = fromUser.relation("Friends");
//add the user the request was to (the accepting user) to the fromUsers friends
relation.add(toUser);
//save the fromUser
fromUser.save(null, {
success: function() {
response.success("saved relation and updated friendRequest");
},
error: function(error) {
response.error(error);
}
});
},
error: function(error) {
response.error(error);
}
});
});
此外,请确保您使用parse deploy
parse 目录中的命令来更新 main.js