views:

235

answers:

1

I have an 3 object hierarchy which has a root as 'Division' that has many 'Group' items and each 'Group' has many 'Employees'.

Division [1]------[*] Group

Group [1]------[*] Employee

I would like to know how to create an NSPredicate to search for all Employees of all Groups of a specific Division, sorted by creation date/time and sectioned in by their 'Group' using the 'Employee' object as the request entity and knowing the id of the specific Division.

But I'm having trouble translating this into CoreData so any suggestions would be helpful.

I were to construct a SQL query, it'd be something like this:

select * from Employee e where e.groupId in (select * from Group g where g.divisionId = :divisionId)

I tried this but didn't work:

    // Create the fetch request for the entity.
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];

    // Configure the request's entity and its predicate.
    NSEntityDescription *entity = [NSEntityDescription 
entityForName:@"Employee" inManagedObjectContext:context];
    [fetchRequest setEntity:entity];

    // Create the predicate
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF.groups IN %@",
    [NSArray arrayWithArray:[[employee groups] allObjects]]];

    [fetchRequest setPredicate:predicate];

    // Edit the sort key as appropriate.
    NSSortDescriptor *createDateSortDcptor = [[NSSortDescriptor alloc] 
initWithKey:@"createDateTime" ascending:YES];

    NSArray *sortDescriptors = [[NSArray alloc] 
initWithObjects:createDateSortDcptor, nil];

    [fetchRequest setSortDescriptors:sortDescriptors];

My Object hierarchy is this:

@interface Division :  NSManagedObject  
{
}

@property (nonatomic, retain) NSDate * createDateTime;
@property (nonatomic, retain) NSSet* groups;

@end

@interface Group :  NSManagedObject  
{
}

@property (nonatomic, retain) NSDate * createDateTime;
@property (nonatomic, retain) Division * division;
@property (nonatomic, retain) NSSet* employees;

@end

@interface Employee :  NSManagedObject  
{
}

@property (nonatomic, retain) NSDate * createDateTime;
@property (nonatomic, retain) NSSet* groups;

@end
A: 

It sounds like you want to create the predicate like

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"ANY SELF.groups IN %@",
                                                          [division groups]];

where division is a Division instance. This will get all eployee instances that have a relationship to any of the division's groups.

Your code to sort the results looks correct.

If you expect to have many such employees, and you want to fetch the result in batches, then your approach using a fetch request is correct. If you're expecting a small number of employees, you can also get them using key-valye coding:

NSArray *divisionEmployees = [division valueForKeyPath:@"@unionOfSets.groups.employees"];
Barry Wark