Phil Loden
Phil Loden

Reputation: 1434

NSPredicate to fetch all objects in a to many relationship

I have a User entity and an Email entity. A user has many emails. If I have a User object, I can access the set of emails with [user emails]. But how can I use an NSPredicate to retrieve all emails for a user? Assume there is no inverse relationship.

Upvotes: 1

Views: 531

Answers (3)

Samuel Goodwin
Samuel Goodwin

Reputation: 1718

You don't need a predicate. You could just take all of your users you care about and do:

[users valueForKey:@"emails"]

and get a pile of all the emails.

Upvotes: 0

J2theC
J2theC

Reputation: 4452

There should be an inverse relationship, or else the program would give you a warning. you can do something like:

NSPredicate *predicate=[NSComparisonPredicate predicateWithLeftExpression:[NSExpression expressionForKeyPath:@"user" rightExpression:[NSExpression expressionForConstantValue:yourUser] modifier:NSDirectPredicateModifier type:NSEqualsToPredicateOperatorType options:0];

Keep in mind that, if you already have the user, you can just get the emails from the user object. An one-to-many relationship is represented in this user object as an NSSet, which you can use either to access all emails from it, or to sort the set into an array. Use the fetch if you need to use an NSFetchResultsController of some sort.

Upvotes: 1

Bruce G
Bruce G

Reputation: 183

Restore the inverse relationship. Core Data wants inverse relationships for its housekeeping even if you don't directly use them.

A simple request against the Email entity would then be:

NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Email"];
[NSPredicate predicateWithFormat:@"user = %@", user];
NSArray *results = [managedObjectContext executeFetchRequest:request error:&error];

Upvotes: 0

Related Questions