1
  • Assuming a Department entity and an Employee entity with a one-many relationship
  • Assuming relationship called employees on Department and department on Employee
  • Assuming Employee has an attribute name

I need to fetch all Departments that don't have an Employee called "Bob"

Based on other answers on SO that I've read, I've tried this:

name = @"Bob";
predicate = [NSPredicate predicateWithFormat:@"ALL employees.name != %@", name];

but it doesn't seem to work. Any ideas?

Thanks.

nick
  • 47
  • 1
  • 5
  • See http://stackoverflow.com/q/5041663/166955 – Geoff Reedy Sep 01 '12 at 21:38
  • No, here is the exact duplicate) http://stackoverflow.com/questions/1347776/how-to-correctly-setup-a-nspredicate-for-a-to-many-relationship-when-using-core – Nikita Pestrov Sep 01 '12 at 22:12
  • Thanks. For the record I needed to change it to: `[NSPredicate predicateWithFormat:@(SUBQUERY(employees, $sub, $sub.name == %@).@count == 0)`, name]; – nick Sep 02 '12 at 00:18
  • 1
    @dnickthomas: A SUBQUERY is not really needed here, see my answer below. – Martin R Sep 02 '12 at 06:12

1 Answers1

6

Do do not need a subquery here:

name = @"Bob";
predicate = [NSPredicate predicateWithFormat:@"NOT ANY employees.name == %@", name];

For some reason, the "ALL" aggregate does not work with to-many relationships, but the "ANY" aggregate works.

Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382