我有一个系统,当前用户接受请求时,我的应用会在发送请求的用户与当前用户之间添加关系。
但是,我还希望将当前用户添加到其他用户的关系中,以便它不仅仅是具有关系的当前用户。
我当前用户的代码有效,但不适用于其他用户。
//i use this pattern to add the requester to a friends relation to the current user
var relation = PFUser.currentUser()!.relationForKey("Friends")
relation.addObject(passenger as PFObject)
PFUser.currentUser()!.saveInBackground()
当我为乘客尝试相同的模式时,它不会添加关系
var relation = passenger.relationForKey("Friends")
relation.addObject(PFUser.currentUser()!.self as PFObject)
passenger.saveInBackground()
修改1:
经过大量研究后,我发现这个答案说我需要云代码。 https://stackoverflow.com/a/23305056/3822504这是唯一的方式还是有替代方案?有人可以提供云代码解决方案吗?
编辑2:
我回答了自己的问题。您需要根据需要编辑云代码。帮助我的最重要的事情是知道如何在云代码中查询用户类并使用云代码获取当前用户。
答案 0 :(得分:0)
这是唯一的方式,afaik。 如果您还没有,请按照本指南设置您的云代码环境:https://parse.com/apps/quickstart#cloud_code/unix
然后你应该定义一个函数(设置后的代码将包含一个样本" hello world"函数,因此你可以从中复制定义)。对于关系修改,您应该参考他们的JS api文档 - https://parse.com/docs/js/api/symbols/Parse.Relation.html
(注意:为了使其正常工作,在您尝试修改用户之前,它应该包含Parse.Cloud.useMasterKey()行)
在您的功能实施并部署了云代码(解析 部署)后,请在您的移动应用中使用PFCloud.callFunctionInBackground。
答案 1 :(得分:0)
好的,过了一会儿,我能够为我的场景找到解决方案。当用户接受另一个用户时,这应该适用于简单的关系。
首先是我的快捷代码。值得注意的是,我创建了一个以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目录中的parse deploy
命令更新main.js