-1

enter image description hereCan I fetch relationship's data in Core Data? The relationship is one-many.

For example: I have 2 entities (department and employee). The department has a to-many employees relationship and employee has a to-one department relationship. I want to get employees of department entity. Can I using fetch function to obtain the data?

Thanks in advance.

4

1 回答 1

0

You can just use the relationship property to get the set of employees for a department:

Department *theDepartment = ...; // your department
NSSet *employeesInDepartment = theDepartment.employees; // set of Employee objects

Or, if you need an array:

NSArray *employeesInDepartment = [theDepartment.employees allObjects];

Alternatively, you can use the following fetch request:

Department *theDepartment = ...; // your department
NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Employee"];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"department = %@", theDepartment];
[request setPredicate:predicate];

NSError *error;
NSArray *employees = [yourManagedObjectContext executeFetchRequest:request error:&error];
于 2013-06-11T11:04:15.700 回答