I have a Core Data model that goes as following:
A ServiceProvider Entity can have many Service Entities(one to many relationship). Each Service has a type attribute.
How can I use the type attribute of the Service entity to search for ServiceProviders that have services with that type?
Below is an example that I currently have that works for a single service relationship. How can I modify the predicate below to work for multiple services?
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSManagedObjectContext* context = [HealthDataManager sharedInstance].managedObjectContext;
NSEntityDescription *entity = [NSEntityDescription entityForName:@"ServiceProvider" inManagedObjectContext:context];
[fetchRequest setEntity:entity];
[fetchRequest setPredicate:[NSPredicate predicateWithFormat:@"self.service.type == %i",type]];
NSArray* results = [context executeFetchRequest:fetchRequest error:nil];
if(results.count>0)
{
for(ServiceProvider* provider in results)
{
DLog(@"found provider: %@", [provider description ]);
}
return [results lastObject];
}else{
DLog(@"Creating provider" );
}
To find objects that have any related service with the given type, use the predicate
[NSPredicate predicateWithFormat:@"ANY services.type == %i",type];
(assuming that "services" is the name of the to-namy relationship).
You need to use subqueries for that: NSPredicate *predicate = [NSPredicate predicateWithFormat:@"(SUBQUERY(service, $service, $service.type == %i).@count) > 0"];.
For more informations about how subqueries and other predicate work you should checkout the Predicate Programming Guide.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With