Reputation: 25711
I have 2 tables in Parse like so:
Users:
(PFUsers table with all Parse data)
belongsToGroups (A Parse Relation to Groups which is many to many)
Groups:
groupId
name
groupMembers (A Parse Relation to Users which is also many to many)
I have the following code:
PFObject *groups = [PFObject objectWithClassName:@"Groups"];
groups[@"name"] = name;
syncUsers[@"isActive"] = [NSNumber numberWithInt:1];
//[groups saveInBackground];
PFUser *current = [PFUser currentUser];
PFRelation *relation = [syncUsers relationforKey:@"groupMembers"];
[relation addObject:current];
[groups saveEventually];
PFRelation *relation2 = [current relationforKey:@"belongsToGroups"];
[relation2 addObject:groups];
[current saveEventually];
First, the top 2 blocks of code work fine, but how do I update the relationship in Users so that I can do View Relation in Parse and see my groups?
Two, do I need to create the Relation in users AND groups so that it can be many to many?
Upvotes: 1
Views: 4092
Reputation: 31
First for a relation you need that both objects exist in the Parse Database. Then you must use the PFRelation object and save the object with the relation.
I recommend using CodeCloud for stablishing relationships so you can share the code with Android or Web Apps.
// Objects
PFObject *student = [PFObject objectWithoutDataWithClassName:@"Student" objectId:@"xauj37H"];
PFObject *teacher = [PFObject objectWithoutDataWithClassName:@"Teacher" objectId:@"xJdcj238"];
// Add a student to the teacher object
// Get the students relation
PFRelation *studentsForTeacher = [teacher relationForKey:@"students"];
// Add a student
[studentsForTeacher addObject:student];
// save the teacher, use InBackground instead
[teacher save];
// Now add a teacher for the student
PFRelation *teachersForStudent = [student relationForKey:@"teachers"];
[teachersForStudent addObject:teacher];
// Save the student
[student save];
// And now you can query the students of a teacher or the teachers of a student
// Students for a Teacher
PFQuery *studentsQuery = [studentsForTeacher query];
[studentsQuery find];
// Teachers for a Student
PFQuery *teachersQuery = [teachersForStudent query];
[teachersQuery find];
Upvotes: 1
Reputation: 2185
You can use whereKey:equalTo:
on a relation column
and pass it a PFObject
. This query will then return all Teacher objects which have this student in their "students" relation:
PFQuery *query = [PFQuery queryWithClassName:@"Teacher"];
[query whereKey:@"students" equalTo:student];
In this example, the student is a PFObject
with a className
that matches the relation in "students". If this is a relation
of PFUsers
and you're looking for the current user's "Teacher"s, you'd use:
PFQuery *query = [PFQuery queryWithClassName:@"Teacher"];
[query whereKey:@"students" equalTo:[PFUser currentUser]];
Upvotes: 1