簡體   English   中英

關於“多對多”和謂詞

[英]About “to-many” and predicate

我有兩個具有“一對多”關系的實體

在此處輸入圖片說明

現在,我想獲取所有僅具有最喜歡的 (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;
}  

但錯誤發生“此處不允許使用多個鍵”

如果您希望類別實例具有一個或多個收藏夾食譜,請嘗試使用ANY關鍵字

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

如果希望類別實例僅包含最喜歡的食譜,則可以使用ALL關鍵字:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM