NSPredicate, get results with a subset of one-to-many relationship

后端 未结 3 1514
旧时难觅i
旧时难觅i 2021-01-07 02:45

I\'mm working around with Core Data and NSFetchedResultsController.

My Data Model looks like this:

Product with one-to-many relat

相关标签:
3条回答
  • 2021-01-07 02:52

    What you want to achieve could be reached in two ways:

    using a SUBQUERY

    [NSPredicate predicateWithFormat:@"SUBQUERY(dataLines, $x, $x.theWeek == %@).@count > 0)", [NSNumber numberWithInt:18]];
    

    or the ANY modifier

    [NSPredicate predicateWithFormat:@"ANY dataLines.theWeek == %@", [NSNumber numberWithInt:18]];
    

    You can do also the following if you need to check against multiple values:

    [NSPredicate predicateWithFormat:@"SUBQUERY(dataLines, $x, $x.theWeek == %@ or $x.theWeek == %@).@count > 0)", [NSNumber numberWithInt:18], [NSNumber numberWithInt:19]];
    

    The same can be applied to ANY modifier. ANY ... OR ANY ....

    Maybe if you share some code we could help you.

    P.S. I suppose you don't use scalar values and theWeek is a number.

    Hope it helps.

    0 讨论(0)
  • 2021-01-07 03:05

    You should fetch the dataLine property instead. Assuming your Product and dataLine entity connected by relationship someRelation then you can try this code;

    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    [fetchRequest setEntity:[NSEntityDescription entityWithName:@"dataLine" inManagedObjectContext:self.managedObjectContext]];
    [fetchRequest setPredicate:[NSPredicate predicateWithFormat:@"dataLines.week == %@",theWeek]];
    
    NSMutableArray *tmpProduct [[NSMutableArray init] alloc];
    NSMutableArray *tmpArray = [self.managedObjectContext executeFetchRequest:fetchRequest error:&error];
    
    for (dataLine *theDataLine in tmpArray);
    NSLog(@"%@",theDataLine.someRelation.name);
    tmpProduct = theDataLine.someRelation.name;
    

    then you can just call tmpProduct to call or display your product in table view

    0 讨论(0)
  • 2021-01-07 03:07

    Create a fetch request for the 'Product' entity:

    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    [fetchRequest setEntity: [NSEntityDescription entityForName:@"Product" ...]]
    

    then create a predicate using the properties/attributes of Product with 'ANY':

    [fetchRequest setPredicate:
      [NSPredicate predicateWithFormat:@"ANY dataLines.theWeek == %@", <whatever week>]];
    

    then execute the fetch to get an array of Product with at least one <whatever week>.

    Generally see 'Fetching Managed Objects', NSPredicate and related documentation.

    0 讨论(0)
提交回复
热议问题