Lets say you have the classic Manager <- Department(s) ->> Employee data model. Where the Manager inherits from the Employee entity which inherits from the Person entity.
If I have a Department, with a Manager and a set of Employees, how can I programmatically represent the Manager losing their job and being demoted to just an Employee, and one of the employees being promoted to the Manager?
In Core Data parlance, I want to take a Managed Object and change its entity, although keep it as a subclass of Person. Is there a smart way to do this? Or will I have to write methods to promote an Employee and demote a Manager like this:
+ (Employee *)demoteManager:(Manager 开发者_如何学Python*)manager {
// Get the context
NSManagedObjectContext *context = [manager managedObjectContext];
// Create a new employee object (mogenerator style)
Employee *employee = [Employee insertIntoManageObjectContext:context];
// Set attributes etc
employee.name = self.name;
// Set relationships etc
Department *dept = manager.manages;
[dept addEmployeesObject:employee];
employee.department = dept;
dept.manager = nil;
manager.manages = nil;
// Delete manager
[context deleteObject:manager];
// Save
NSError *error = nil;
[context save:&error];
return employee;
}
etc? And I realise that I should just put a boolean flag on Employee (isManager), but this is a contrived example for this question, in reality I don't want to use a flag.
So, if some Core Data wizards have done this already or know a better way, I'd love to hear!
Cheers,
There is no way to change an entity like you are describing. You would need to create a new employee, copy the manager's data to that employee record and create a new manager for the promoted employee.
However, as Christian suggested, it would be better if your manager was also an employee. You mentioned additional data that is manager specific. Perhaps you could put this into a third table that has a relationship to a specific employee. Then any employee that is also a manager will have data stored in this auxiliary table. Far less painful than destroying and creating objects just to promote or demote a manager.
You can't change the type of an Entity in Core Data, AFAIK.
What's the difference between a Manager
and an Employee
? Isn't a Manager
also an Employee
? Isn't a Manager
an Employee
with the role Manager
?
For my understanding I would model it like this:
Department(s) ->> Employee
and the Department
has an attribute manager
that's a 1:1 relationship to Employee
, defining what employee is the manager.
精彩评论