2009-10-16 82 views
1

我有一個3個對象層次結構,其根具有許多'Group'項目'Division',每個'Group'有許多'Employees'。如何設置此查詢的謂詞

司[1] ------ [*]集團

集團[1] ------ [*]員工

我想知道如何創建NSPredicate以搜索特定分部的所有組的所有員工,按照創建日期/時間進行排序,並使用「員工」對象作爲請求實體並知道特定分部的ID,將其分組爲「組」。

但是我很難將其轉換成CoreData,所以任何建議都會有幫助。

我是構建一個SQL查詢時,它會是這樣的:

SELECT * FROM僱員e其中 e.groupId在(SELECT * FROM G組 其中g.divisionId =: divisionId)

我試過,但沒有奏效:

// 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]; 

我的對象的層次結構是這樣的:

@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 

回答

0

這聽起來像你想創建的斷言像

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

了分割是一個分部實例。這將獲得與任何部門組有關係的所有eployee實例。

您的代碼對結果排序看起來正確。

如果您希望有很多這樣的員工,並且想要批量獲取結果,那麼您使用獲取請求的方法是正確的。如果你期望少數員工,你也可以使用key-valye編碼得到他們:

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