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

十年热恋 提交于 2019-12-09 01:41:13

问题


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?


回答1:


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.




回答2:


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




回答3:


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.



来源:https://stackoverflow.com/questions/10857930/nspredicate-get-results-with-a-subset-of-one-to-many-relationship

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!