Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parse - saving related objects

I'm using Parse for the back end in my project.

As you would imagine there are quite a few relations in the data model. A lot of the time I create a "parent" object and all of its "children" at the same moment and save them all to Parse.

Now, when doing this is it necessary to save the children individually? The same for files etc...

First example - Adding an avatar to a user object

UIImage *image = // image from camera
NSData *pngData = UIImagePNGRepresentation(image);
PFFile *imageFile = [PFFile fileWithData:pngData];
[[PFUser currentUser] setObject:imageFile forKey:"avatar"];

OK, so on the device I can reference the @"avatar" key on the user and get the avatar file. But how should this be saved to Parse?

If I do...

[[PFUser currentUser] saveInBackground];

Will this save the new file that was added? Or do I need to save the file first and wait for this to succeed before then adding it into the user object and then saving the user object?

Second example

Creating a tree of objects...

PFObject *family = [PFObject objectWithClassName:@"Family"];
[family setObject:@"Smith" forKey:@"familyName"];

PFObject *person1 = [PFObject objectWithClassName:@"Person"];
[person1 setObject:@"Bob" forKey:@"name"];

PFObject *person2 = [PFObject objectWithClassName:@"Person"];
[person2 setObject:@"Alice" forKey:@"name"];

PFObject *person3 = [PFObject objectWithClassName:@"Person"];
[person3 setObject:@"Chris" forKey:@"name"];

[family setObject:@[person1, person2, person3] forKey:@"members"];

How would I save this collection of objects?

Can I just do [family saveInBackground];?

Or do I have to go through a process of saving every Person object first and checking that it worked before saving the family object?

like image 890
Fogmeister Avatar asked Oct 20 '22 08:10

Fogmeister


1 Answers

As long as the relationship between parent and child is Pointer, you don't have to save the child first. PFRelation works differently, but a save on the parent object will also save children related as pointers. This is true for Cloud Code, and I am pretty sure it holds true for the device as well.

Some details in this answer: https://www.parse.com/questions/cloud-code-efficient-hierarchy-saving

like image 133
Marius Waldal Avatar answered Oct 23 '22 01:10

Marius Waldal