0

I have three entities: Session, User and Test. A session has 0-many users and a user can perform 0-6 tests. (I say 0 but in the real application always at least 1 is required, at least 1 user for a session and at least 1 test for a user. But I say 0 to express an empty start.) All entities have their own specific data attributes too. A user has a name, A session has a name, a test has six values to be filled in by the user, and so on. But my issue is with the relationships.

  1. How do I set multiple users and have them added to one session (same goes for multiple tests for one user).

  2. How do I show the content in a right way? How do I show a session that has multiple users and these users having completed multiple tests?

Here's my code so far with regard to issue 1:

Session *session = [NSEntityDescription insertNewObjectForEntityForName:@"Session"
                                  inManagedObjectContext:context];
session.name = @"Session 1";

User *users = [NSEntityDescription insertNewObjectForEntityForName:@"User"
                                   inManagedObjectContext:context];
users.age = [NSNumber numberWithInt:28];
users.session = session;
//session.user = users;
[sessie addUserObject:users];

With regard to issue 2: I can log the session, but I can't get the user(s) logged from a session.

NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Session"
                                          inManagedObjectContext:context];
[fetchRequest setEntity:entity];
NSArray *fetchedObjects = [context executeFetchRequest:fetchRequest error:&error];
for (Session *info in fetchedObjects) {
 NSLog(@"Name of session: %@", info.name);
 NSLog(@"Having problems with this: %@",info.user);
 //User *details = info.user;
 //NSLog(@"User: %@", details.age);
}
4

1 回答 1

2

我发现它很有用(从我在 SO 看到的代码示例中,这似乎是常见的做法),将复数形式用于对多关系,例如usersSessionUser的对多关系。它强调了关系的值是一个集合而不是单个对象的事实,并且可能会使事情更清楚一些。

所以你的模型看起来像这样:

在此处输入图像描述

问题 1:如果您创建了 aSession *session和 a User *user,那么

user.session = session;

将用户添加到会话。打电话

[session addUsersObject:user];

有同样的效果。但是只需要这些调用中的一个,如果关系被正确定义为反向关系,它会自动暗示另一个。

问题 2:对于 a Session *sessionsession.users是与该会话相关的所有用户的集合。它是一个NSSet,您可以遍历该集合。同样,user.tests是用户的所有测试的集合。

因此,以下代码显示了与其用户和测试的所有会话:

NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Session"
                                          inManagedObjectContext:context];
[fetchRequest setEntity:entity];

NSArray *sessions = [context executeFetchRequest:fetchRequest error:&error];
for (Session *session in sessions) {
    NSLog(@"Name of session: %@", session.name);
    for (User *user in session.users) {
        NSLog(@"   User name %@, age %@", user.name, user.age);
        for (Test *test in user.tests) {
            NSLog(@"      Test: %@", test.name);

        }
    }
}
于 2012-12-15T07:16:59.357 回答