karlofk
karlofk

Reputation: 1215

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

I'mm working around with Core Data and NSFetchedResultsController.

My Data Model looks like this:

Product with one-to-many relationship called dataLines. The dataLine entity has a property name theWeek.

I want to fetch all Product where dataLines.theWeek == someValue. This is easily done with a subquery. But this returns all dataLines. Is it possible to create a NSPredicate that returns the Product and a subset if dataLines only with the dataLines == someValue?

Upvotes: 2

Views: 2918

Answers (3)

Lorenzo B
Lorenzo B

Reputation: 33428

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.

Upvotes: 8

usergio2
usergio2

Reputation: 469

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

Upvotes: 1

GoZoner
GoZoner

Reputation: 70235

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.

Upvotes: 0

Related Questions