我可以在Core Data中获取关系数据吗? 这种关系只有一个。
例如:我有2个实体(部门和员工)。该部门与员工关系多,员工之间有一对一的部门关系。我想得到部门实体的员工。我可以使用fetch函数来获取数据吗?
提前致谢。
答案 0 :(得分:0)
您可以使用relationship属性获取部门的员工集:
Department *theDepartment = ...; // your department
NSSet *employeesInDepartment = theDepartment.employees; // set of Employee objects
或者,如果你需要一个数组:
NSArray *employeesInDepartment = [theDepartment.employees allObjects];
或者,您可以使用以下获取请求:
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];