1

我在 Parse 中有 2 个表,如下所示:

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)

我有以下代码:

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];

首先,前 2 个代码块工作正常,但是如何更新用户中的关系,以便我可以在 Parse 中查看关系并查看我的组?

二,我是否需要在用户和组中创建关系以便它可以是多对多的?

4

2 回答 2

1

您可以whereKey:equalTo:在关系上使用column并将其传递给PFObject. 然后,此查询将返回在其“学生”关系中包含该学生的所有教师对象:

PFQuery *query = [PFQuery queryWithClassName:@"Teacher"];
[query whereKey:@"students" equalTo:student];

在此示例中,学生是一个PFObjectclassName“学生”中的关系匹配的 a。如果这是一个relationPFUsers并且您正在寻找当前用户的“老师”,您将使用:

PFQuery *query = [PFQuery queryWithClassName:@"Teacher"];
[query whereKey:@"students" equalTo:[PFUser currentUser]];
于 2014-04-24T07:57:47.897 回答
1

首先,对于一个关系,您需要两个对象都存在于 Parse 数据库中。然后您必须使用 PFRelation 对象并将对象与关系一起保存。

我建议使用 CodeCloud 来建立关系,以便您可以与 Android 或 Web 应用程序共享代码。

// 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];
于 2014-04-24T19:34:13.003 回答