I'm wanting to make a CoreData entity called "Employees", some "Employees" could have a line manager (or boss).
In basic pseducode, it could be described as:
emp_id (PRIMARY KEY)
emp_name
emp_parent_id (INT *but optional as some people may not have line managers*)
开发者_如何学PythonAnother example I could use is "articles" an Article could have a parent "article", of course not all articles have a parent article.
The issue I'm having is, I'm not sure how to represent this in Core Data, or even if it can handle such things.
In the Core Data Model maker, I create an entity called "Employee" and then make a relationship which points to itself with optional checked and ensure that there is no cascading deletes, or no inverse relationship.
I am unsure if this is the right way to do it though. Can I make a core data entity relate to itself as an optional parent?
Thanks.
Sure you can. But you also should add the inverse relationship, so you can find out all the employees a manager is manager of.
Your employee entity should look somewhat like this:
- Relationship manager: to-one, optional, inverse: managedEmployees
- Relationship managedEmployees: to-many, optional, inverse: manager
I've been able to do a basic version with 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]
Although I am still learning the basics of Core Data.
@Sven - I cannot force the to-Many relationship, it always gives me many-to-many. So for the moment I am just using 1-to-1 relationship.
精彩评论