单个实体核心数据获取请求的SQL语句

时间:2012-12-19 18:45:48

标签: mysql ios core-data nsfetchrequest

我在Entity中有一个CoreData模仿MySQL数据库表,其结构如下:

Photo
    abv            Double
    photoId        Integer16
    photographer   String
    isActive       Boolean
    lastUpdated    Data
    name           String

我可以运行以下SQL语句来获得我想要的结果集:

SELECT  `photographerName`, COUNT(`photographerName`) 
FROM  `Photos` 
WHERE  `isActive` LIKE 1
GROUP BY  `photographerName` 
ORDER BY  `photographerName` 

我可以使用NSFetchRequestNSSortDescriptorNSPredicateNSExpressionDescription的哪种组合来在iOS中获得相同的结果?

我使用以下内容:

NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Photo"];
NSSortDescriptor *photographerSortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"photographer" ascending:YES selector:@selector(localizedCaseInsensitiveCompare:)];
NSPredicate *onlyActivePhotos = [NSPredicate predicateWithFormat:@"isActive == 1"];

request.sortDescriptors = @[photographerSortDescriptor];
request.predicate = onlyActivePhotos;

self.fetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:request managedObjectContext:self.managedObjectContext sectionNameKeyPath:nil cacheName:nil];

这让我isActive罚款,但每Photo只返回一行,而不是Photographer

或者......我应该将其分成两个Entities吗?例如,PhotographerPhotos有一对多的关系?

1 个答案:

答案 0 :(得分:1)

首先,建立关系Photo - Photographer肯定是更好,更灵活的设计。

然而,您也可以实现您想要的。您只能获取照片实体,因此必须过滤生成的数组后才能返回您的摄影师名称。

NSArray *photographerNames = [fetchedResultsController.fetchedObjects
   valueForKeyPath:"@photographer"];
NSSet *uniqueNames = [NSSet setWithArray:photographerNames];
NSArray *orderedNames = [uniqueNames sortedArrayUsingDescriptors:
   @[[NSSortDescriptor sortDescriptorWithKey:@"self" ascending:YES]]]; 

如您所见,这非常麻烦。此外,您丢失了与每位摄影师相关的照片信息。

所以请继续关系。毕竟,Core Data是一个对象图,而不是数据库包装器。