【问题标题】:How to setup a predicate for this query如何为此查询设置谓词
【发布时间】:2009-10-16 20:31:41
【问题描述】:

我有一个 3 对象层次结构,其根为“部门”,有许多“组”项,每个“组”有许多“员工”。

部门 [1]------[*] 组

组 [1]------[*] 员工

我想知道如何创建一个 NSPredicate 来搜索特定部门所有组的所有员工,按创建日期/时间排序,并使用“员工”对象作为请求实体按他们的“组”划分并知道特定部门的 id。

但我无法将其转换为 CoreData,因此任何建议都会有所帮助。

我要构造一个 SQL 查询,它会是这样的:

select * from Employee e where e.groupId in (select * from Group 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

【问题讨论】:

    标签: iphone core-data


    【解决方案1】:

    听起来你想创建谓词

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

    其中 Division 是一个 Division 实例。这将获取与任何部门的组有关系的所有员工实例。

    您对结果进行排序的代码看起来是正确的。

    如果您希望有很多这样的员工,并且您希望批量获取结果,那么您使用获取请求的方法是正确的。如果您预计员工人数较少,您也可以使用键值编码获得他们:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-09-12
      • 1970-01-01
      相关资源
      最近更新 更多