Search code examples
iosobjective-ccore-datanspredicatensfetchrequest

Verifying many to many relationships using NSPredicate


I have 2 tables like so:

 Users
 user_id (pk)
 email
 name
 inGroups (many to many relationship with groups)

 Groups
 group_id (pk)
 group_name
 whoseUsers (many to many relationship with users) 

I have my core data code as so:

NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Users"];
request.predicate = [NSPredicate predicateWithFormat:@"user_id = %@ AND inGroups = %@", user_id, group_id];

When this is run I get an exception thrown:

@"to-many key not allowed here"

How do I get this to work properly?


Solution

  • To find users with a given user_id that are members of a group with the given group_id, use

    [NSPredicate predicateWithFormat:@"user_id = %@ AND ANY inGroups.group_id = %@",
                                       user_id, group_id];