关于“to-many”和谓词

时间:2013-02-27 03:56:49

标签: ios core-data nspredicate one-to-many

我有两个“to-many”关系的实体

enter image description here

现在我想获取所有仅包含收藏(isFavorite)食谱的类别。

这就像:

SELECT c.*  
FROM zcategories c, zrecipes r
where 
    r.zisfavorite = 1
    and r.zincategory = c.z_pk
group by c.zname;

我试过

    - (NSFetchedResultsController *)fetchedResultsController
{
    if (__fetchedResultsController != nil) {
        return __fetchedResultsController;
    }

    AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    self.checkedMOC = appDelegate.managedObjectContext;

    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    // Edit the entity name as appropriate.
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"Categories" inManagedObjectContext:self.checkedMOC];
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"ALL recipes.isFavorite == %@", [NSNumber numberWithInt:1]];
    [fetchRequest setEntity:entity];
    [fetchRequest setPredicate:predicate];

    // Set the batch size to a suitable number.
    [fetchRequest setFetchBatchSize:20];

    // Edit the sort key as appropriate.
    NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"name" ascending:YES];
    NSArray *sortDescriptors = [NSArray arrayWithObjects:sortDescriptor, nil];

    [fetchRequest setSortDescriptors:sortDescriptors];

    // Edit the section name key path and cache name if appropriate.
    // nil for section name key path means "no sections".
    NSFetchedResultsController *aFetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:self.checkedMOC sectionNameKeyPath:nil cacheName:@"Master"];
    aFetchedResultsController.delegate = self;
    self.fetchedResultsController = aFetchedResultsController;

    NSError *error = nil;
    if (![self.fetchedResultsController performFetch:&error]) {
        // Replace this implementation with code to handle the error appropriately.
        // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. 
        NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
        abort();
    }

    return __fetchedResultsController;
}  

但错误发生'这里不允许使用多个密钥'

1 个答案:

答案 0 :(得分:1)

如果您想要包含一个或多个收藏的食谱的类别实例,请尝试使用ANY关键字

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"ANY recipes.isFavorite == %@", [NSNumber numberWithInt:1]];

如果您想要仅包含收藏的食谱的类别实例,您可以使用ALL关键字:

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"ALL recipes.isFavorite == %@", [NSNumber numberWithInt:1]];