CoreData - 如何使实体与自身建立父子关系?

时间:2010-09-28 11:20:35

标签: objective-c core-data parent-child

我想创建一个名为“Employees”的CoreData实体,一些“Employees”可能有一个直线经理(或老板)。

在基本的pseducode中,它可以描述为:

emp_id (PRIMARY KEY)
emp_name
emp_parent_id (INT *but optional as some people may not have line managers*)

我可以使用的另一个例子是“文章”,文章可以有父文章“文章”,当然并非所有文章都有父文章。

我遇到的问题是,我不确定如何在Core Data中表示这一点,或者即使它可以处理这些事情。

在核心数据模型制作者中,我创建了一个名为“Employee”的实体,然后创建一个指向自身的关系,并选择了checked,并确保没有级联删除或没有反向关系。

我不确定这是否是正确的做法。我可以将核心数据实体与自身相关联作为可选父级吗?

感谢。

2 个答案:

答案 0 :(得分:3)

当然可以。但您也应该添加反向关系,这样您就可以找到经理所管理的所有员工。

您的员工实体应该看起来像这样:

  • 关系经理:to-one,optional,inverse:managedEmployees
  • 关系managedEmployees:to-many,optional,inverse:manager

答案 1 :(得分:0)

我已经能够使用NSLog做基本版本。

NSManagedObjectContext *context = [self managedObjectContext];

Employee *boss = [NSEntityDescription insertNewObjectForEntityForName:@"Employee" 
                           inManagedObjectContext:context];
boss.name = @"Mr Big";

Employee *emp = [NSEntityDescription insertNewObjectForEntityForName:@"Employee" 
                          inManagedObjectContext:context];
emp.name = @"Mr Smith";
emp.parent_emp = boss;

NSError *error;
if (![context save:&error])
{
NSLog(@"Error -- %@", [error localizedDescription] );
}

// Now we loop through each entity
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Employee" inManagedObjectContext:context];
[fetchRequest setEntity:entity];
NSArray *fetchedObjects = [context executeFetchRequest:fetchRequest error:&error];

for (NSManagedObject *info in fetchedObjects) {
NSLog(@"Name: %@", [info valueForKey:@"name"]);
NSEntityDescription *parent = [info valueForKey:@"parent_emp"];
NSLog(@"Parent: %@", parent.name );
NSLog(@"------------");   
}

[fetchRequest release]

虽然我还在学习核心数据的基础知识。

@Sven - 我无法强迫to-Many关系,它总是给我多对多。所以目前我只是使用一对一的关系。