trundrumbalind
trundrumbalind

Reputation: 83

CoreData - NSFetchRequest AND Filter On Child Relationship Entities

Ok, say I have many entities of type "Office" and it has a relationship called "employees" which is a to-many relationship containing "Employee" objects. "Employee" has an attribute called "lastName".

Given that, I need to do a fetch that returns an array of Office objects which have > 0 employees but in the returned Offices, the Employee objects inside the employees relationship has been filtered down to include only Employee objects where the lastName equals "Smith".

I could easily just get all the Office objects and then iterate through them and remove all the employees whose name doesn't match Smith however that would delete those objects in the store.

I'm assuming SUBQUERY is required here but I can't seem to get it filtering correctly. Any ideas?

Upvotes: 0

Views: 459

Answers (1)

Léo Natan
Léo Natan

Reputation: 57050

You want a SUBQUERY in your predicate.

[NSPredicate predicateWithFormat:@"SUBQUERY(employees, lastName, lastName LIKE[cd] %@).@count > 0", @"Smith"]

This performs a subquery on each employees relationship, testing lastName for the provided string, and counting that there is at least one such employee.

Upvotes: 2

Related Questions